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];