在Apache HttpClient中使用HttpRequestInterceptor操作请求实体

时间:2014-12-17 01:43:13

标签: apache apache-httpclient-4.x

HttpRequest没有让Request实体的getter允许我在拦截器中操作它。使用instanceof检查类型也不起作用。有人会对我如何做到这一点有任何想法吗?

public class FastinfosetRequestInterceptor implements HttpRequestInterceptor 
{

@Override
public void process(HttpRequest request, HttpContext context)
        throws HttpException, IOException 
{
    if(request instanceof HttpPost)
    {
        HttpEntity rqEntity = ((HttpPost)request).getEntity();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        rqEntity.writeTo(baos);
        byte[] encodedRq;
        try 
        {
            encodedRq = FastInfosetUtils.encodeToFastInfoSet(baos.toByteArray());
        } 
        catch (ParserConfigurationException | SAXException
                | TransformerException e) 
        {
            throw new IOException("Error while encoding request to FastInfoSet", e);
        }
        ((HttpPost) request).setEntity(new ByteArrayEntity(encodedRq));
    }
}
}

1 个答案:

答案 0 :(得分:1)

这应解决问题

if(request instanceof HttpEntityEnclosingRequest)
{
    HttpEntity rqEntity = ((HttpEntityEnclosingRequest) request).getEntity();