使用Apache HttpClient,可以通过添加HttpResponseIntercepter
来操纵检索到的内容。有了它,添加标头属性非常容易。但是如何操纵检索到的HttpEntity
的内容?
例如,我喜欢将所有文本转换为大写。
@Test
public void shoudConvertEverythingToUpperCase() throws ClientProtocolException, IOException
{
final DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException
{
final HttpEntity entity = response.getEntity();
final HttpEntity upperCaseEntity = makeAllUppercase(entity);
response.setEntity(upperCaseEntity);
}
private HttpEntity makeAllUppercase(final HttpEntity entity)
{
// how to uppercase everything and return the cloned HttpEntity
return null;
}
});
final HttpResponse httpResponse = defaultHttpClient.execute(new HttpGet("http://stackoverflow.com"));
assertTrue(StringUtils.isAllUpperCase(EntityUtils.toString(httpResponse.getEntity())));
}
答案 0 :(得分:1)
private HttpEntity makeAllUppercase(final HttpEntity entity)
{
Header h = entity.getContentType();
ContentType contentType = h != null ? ContentType.parse(h.getValue()) : ContentType.DEFAULT_TEXT;
String content = EntityUtils.toString(entity, contentType.getCharset());
return new StringEntity(content.toUpperCase(Locale.US), contentType);
}
由于内存中的内容缓冲是最有效的,但是最简洁的实现。