【问题标题】:Get all the headers for HttpPost with entity使用实体获取 HttpPost 的所有标头
【发布时间】:2016-08-18 03:37:16
【问题描述】:

我正在使用 HttpClient 向 Azure 发送带有正文的 PUT 请求。 主体由 StringEntity 表示。

我需要将 Azure 身份验证签名添加到请求中,为了正确计算它,我需要 Content-Type 和 Content-Length 标头的值。

在 HttpPost 请求上调用 setEntity() 方法时,请求中没有添加任何标头,但使用 HTTP 调试代理我可以看到它们已正确随请求一起发送。

从 Apache 文档 (here) 我看到我可以使用 entity.getContentLength() 和 entity.getContentType() 来计算它们,但如果可能的话,我更愿意直接从 HttpPost 中提取数据。

有谁知道在执行请求之前强制实体将标头添加到请求中的方法?

这是我正在使用的代码

HttpPut createBlob = new HttpPut(createBlobUrl);
createBlob.addHeader("x-ms-blob-type", "BlockBlob");
createBlob.addHeader("x-ms-date", utcTime);
createBlob.addHeader("x-ms-version", "2015-04-05");

HttpEntity body =  new StringEntity("test blob", "UTF-8");
createBlob.setEntity(body);

// h is missing Content-Length and Content-Type
Header[] h = createBlob.getAllHeaders();

resp = httpclient.execute(createBlob);

【问题讨论】:

    标签: java apache-httpclient-4.x


    【解决方案1】:

    我找到了解决办法。

    向客户端添加拦截器,我可以在它执行之前获得带有所有标头的完整请求,因此我不需要处理实体添加标头的特殊情况。

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder = builder.disableContentCompression().disableConnectionState();
    
    builder.addInterceptorLast((HttpRequestInterceptor) (request, context) -> {
        try {
            SignRequest(request, account, secret);
         }
         catch (Exception e) {
         }
    });
    
    HttpClient httpclient = builder.build();
    

    拦截器官方教程见at this link

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多