Merge pull request #633 from gijsbert802/use-charset-from-http-header-2

Use the charset from the content-type header of the HttpRequest instead of always using the default charset.
This commit is contained in:
James Agnew 2017-05-20 17:59:03 -04:00 committed by GitHub
commit 9ca8a285b9
2 changed files with 43 additions and 2 deletions

View File

@ -33,6 +33,7 @@ import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import ca.uhn.fhir.rest.client.api.IHttpRequest;
import ca.uhn.fhir.rest.client.api.IHttpResponse;
@ -93,8 +94,9 @@ public class ApacheHttpRequest implements IHttpRequest {
if (myRequest instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) myRequest).getEntity();
if (entity.isRepeatable()) {
//TODO verify the charset
return IOUtils.toString(entity.getContent(), Charset.defaultCharset());
final Header contentTypeHeader = myRequest.getFirstHeader("Content-Type");
Charset charset = contentTypeHeader == null ? null : ContentType.parse(contentTypeHeader.getValue()).getCharset();
return IOUtils.toString(entity.getContent(), charset);
}
}
return null;

View File

@ -0,0 +1,39 @@
package ca.uhn.fhir.rest.client.apache;
import static org.junit.Assert.assertEquals;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
public class ApacheHttpRequestTest {
private final String ENTITY_CONTENT = "Some entity with special characters: é";
private StringEntity httpEntity;
private HttpPost apacheRequest = new HttpPost("");
@Test
public void testGetRequestBodyFromStream() throws IOException {
httpEntity = new StringEntity(ENTITY_CONTENT, Charset.forName("ISO-8859-1"));
apacheRequest.setHeader("Content-type", "text/plain; charset=ISO-8859-1");
apacheRequest.setEntity(httpEntity);
String result = new ApacheHttpRequest(null, apacheRequest).getRequestBodyFromStream();
assertEquals(ENTITY_CONTENT, result);
}
@Test
public void testGetRequestBodyFromStreamWithDefaultCharset() throws IOException {
httpEntity = new StringEntity(ENTITY_CONTENT, Charset.defaultCharset());
apacheRequest.setHeader("Content-type", "text/plain");
apacheRequest.setEntity(httpEntity);
String result = new ApacheHttpRequest(null, apacheRequest).getRequestBodyFromStream();
assertEquals(ENTITY_CONTENT, result);
}
}