This commit is contained in:
bgoorden 2024-09-26 10:43:19 -04:00 committed by GitHub
commit 9aaeca6efb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 37 additions and 3 deletions

View File

@ -26,8 +26,10 @@ import ca.uhn.fhir.rest.client.api.IHttpResponse;
import ca.uhn.fhir.util.StopWatch;
import okhttp3.Call;
import okhttp3.Call.Factory;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;
import java.io.IOException;
import java.util.Collections;
@ -80,9 +82,16 @@ public class OkHttpRestfulRequest extends BaseHttpRequest implements IHttpReques
}
@Override
public String getRequestBodyFromStream() {
// returning null to indicate this is not supported, as documented in IHttpRequest's contract
return null;
public String getRequestBodyFromStream() throws IOException {
if (myRequestBody == null) {
return null;
}
final Buffer buffer = new Buffer();
myRequestBody.writeTo(buffer);
MediaType contentType = myRequestBody.contentType();
return contentType == null || contentType.charset() == null
? buffer.readUtf8()
: buffer.readString(contentType.charset());
}
@Override

View File

@ -1,12 +1,19 @@
package ca.uhn.fhir.okhttp.client;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class OkHttpRestfulRequestTest {
private final String ENTITY_CONTENT = "Some entity with special characters: é";
@Test
void toString_afterCreation_GetUsefulDataForLogging() {
String theUrl = "https://example.com/fhir/meta";
@ -24,4 +31,22 @@ public class OkHttpRestfulRequestTest {
OkHttpRestfulRequest okHttpRestfulRequest = new OkHttpRestfulRequest(clientFactory.getNativeClient(), theUrl, RequestTypeEnum.POST, null);
assertEquals("POST https://another.example.com/fhir/Task", okHttpRestfulRequest.toString());
}
@Test
public void testGetRequestBodyFromStream() throws IOException {
RequestBody requestBody = RequestBody.create(ENTITY_CONTENT.getBytes(StandardCharsets.ISO_8859_1), MediaType.parse("text/plain; charset=ISO-8859-1"));
String result = new OkHttpRestfulRequest(null, "https://test.com", null, requestBody).getRequestBodyFromStream();
assertEquals(ENTITY_CONTENT, result);
}
@Test
public void testGetRequestBodyFromStreamWithUnknownCharset() throws IOException {
RequestBody requestBody = RequestBody.create(ENTITY_CONTENT.getBytes(StandardCharsets.UTF_8), MediaType.parse("text/plain; charset=UTF-8"));
String result = new OkHttpRestfulRequest(null, "https://test.com", null, requestBody).getRequestBodyFromStream();
assertEquals(ENTITY_CONTENT, result);
}
}