[java][okhttp-gson] Complex values in form data get serialized as JSON instead of String (#12779)

* Java: fix complex object serialization in form-data

* Java: update samples
This commit is contained in:
Linus Klöckner
2022-07-13 09:47:39 +02:00
committed by GitHub
parent 9e2b8a0ec1
commit 57496ff0b0
6 changed files with 174 additions and 18 deletions

View File

@@ -1401,11 +1401,12 @@ public class ApiClient {
for (Object item: list) {
if (item instanceof File) {
addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item);
} else {
addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue());
}
}
} else {
Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
mpBuilder.addPart(partHeaders, RequestBody.create(parameterToString(param.getValue()), null));
addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue());
}
}
return mpBuilder.build();
@@ -1439,6 +1440,31 @@ public class ApiClient {
mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType));
}
/**
* Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder.
*
* @param mpBuilder MultipartBody.Builder
* @param key The key of the Header element
* @param obj The complex object to add to the Header
*/
private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) {
RequestBody requestBody;
if (obj instanceof String) {
requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain"));
} else {
String content;
if (obj != null) {
content = json.serialize(obj);
} else {
content = null;
}
requestBody = RequestBody.create(content, MediaType.parse("application/json"));
}
Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"");
mpBuilder.addPart(partHeaders, requestBody);
}
/**
* Get network interceptor to add it to the httpClient to track download progress for
* async requests.
@@ -1608,7 +1634,7 @@ public class ApiClient {
/**
* Convert the HTTP request body to a string.
*
* @param request The HTTP request object
* @param requestBody The HTTP request object
* @return The string representation of the HTTP request body
* @throws org.openapitools.client.ApiException If fail to serialize the request body object into a string
*/