From 7665727512eb558bcf37a5c72a0dab29a2eef221 Mon Sep 17 00:00:00 2001 From: Chace Daniels Date: Fri, 8 Dec 2023 12:11:06 -0600 Subject: [PATCH] fix(http): properly write form-urlencoded data on android request body (#7001) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Mark Anderson Co-authored-by: Dan Giralté <97970732+giralte-ionic@users.noreply.github.com> --- .../util/CapacitorHttpUrlConnection.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/android/capacitor/src/main/java/com/getcapacitor/plugin/util/CapacitorHttpUrlConnection.java b/android/capacitor/src/main/java/com/getcapacitor/plugin/util/CapacitorHttpUrlConnection.java index 3f4ee8055a..161a74d45e 100644 --- a/android/capacitor/src/main/java/com/getcapacitor/plugin/util/CapacitorHttpUrlConnection.java +++ b/android/capacitor/src/main/java/com/getcapacitor/plugin/util/CapacitorHttpUrlConnection.java @@ -215,6 +215,14 @@ public void setRequestBody(PluginCall call, JSValue body, String bodyType) throw } os.flush(); } + } else if (contentType.contains("application/x-www-form-urlencoded")) { + try { + JSObject obj = body.toJSObject(); + this.writeObjectRequestBody(obj); + } catch (Exception e) { + // Body is not a valid JSON, treat it as an already formatted string + this.writeRequestBody(body.toString()); + } } else if (bodyType != null && bodyType.equals("formData")) { this.writeFormDataRequestBody(contentType, body.toJSArray()); } else { @@ -234,6 +242,24 @@ private void writeRequestBody(String body) throws IOException { } } + private void writeObjectRequestBody(JSObject object) throws IOException, JSONException { + try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) { + Iterator keys = object.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object d = object.get(key); + os.writeBytes(key); + os.writeBytes("="); + os.writeBytes(URLEncoder.encode(d.toString(), "UTF-8")); + + if (keys.hasNext()) { + os.writeBytes("&"); + } + } + os.flush(); + } + } + private void writeFormDataRequestBody(String contentType, JSArray entries) throws IOException, JSONException { try (DataOutputStream os = new DataOutputStream(connection.getOutputStream())) { String boundary = contentType.split(";")[1].split("=")[1];