1
使用Apache HttpClient,可以通過添加HttpResponseIntercepter
來操作檢索到的內容。有了這個,添加標題屬性是很容易的。但是如何操作檢索到的HttpEntity
的內容呢?使用HttpResponseInterceptor處理響應
例如我喜歡將所有文本轉換爲大寫。
@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())));
}