Skip to content

Commit

Permalink
fix(http): properly write form-urlencoded data on android request body (
Browse files Browse the repository at this point in the history
#7130)

Co-authored-by: Chace Daniels <[email protected]>
Co-authored-by: Mark Anderson <[email protected]>
Co-authored-by: Dan Giralté <[email protected]>
  • Loading branch information
4 people authored Dec 14, 2023
1 parent dfc97ee commit a745a89
Showing 1 changed file with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<String> 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];
Expand Down

0 comments on commit a745a89

Please sign in to comment.