HttpHeaders没有在HTTPResponse中设置

时间:2016-06-30 14:31:33

标签: java post http-headers httpclient

我正在尝试使用默认的HttpClient

在Java中实现以下curl命令
curl  -H "Content-Type:application/json"  -H "Authorization:Bearer rAnDoMSrings-" -X POST -d  @example.json http://api.rest.company.com/

这是Java中的客户端

    DefaultHttpClient httpclient = null;
    HttpResponse response = null;

    try {
        httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(apiUrl);
        post.setHeader("Content-Type","application/json");
        post.addHeader("Authorization", "Bearer " +authToken);
        JSONObject json = new JSONObject();
        json.put("image_url", ");
        // Required field.
        json.put("job_fqn",");
        JSONArray routesJsonArray = new JSONArray();
        routesJsonArray.put(0, "");
        json.put("routes",routesJsonArray);
        StringEntity params = new StringEntity(json.toString());
        post.setEntity(params);

        response = httpclient.execute(post);
    }
    catch (Exception e) {
        System.out.println("Exception" + e);
    }
    finally {
        httpclient.getConnectionManager().shutdown();
    }

}

这会产生401 Unauthorized错误。经过一些调试后,我发现没有一个标题被识别,我得到了以下内容

DEBUG [2016-06-30 14:24:16,559] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges

请注意,curl命令工作正常。我错过了什么?

请注意,传出标头设置正确,我可以将它们从请求对象中注销

这是堆栈跟踪

DEBUG [2016-06-30 17:51:08,665] org.apache.http.wire: >> "POST /v1/api HTTP/1.1[\r][\n]"
DEBUG [2016-06-30 17:51:08,665] org.apache.http.wire: >> "Content-Type: application/json[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Authorization: Bearer correct_token; Path=/; Domain=auth.server; Expires=Fri, 01 Jul 2016 17:51:08 UTC[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Content-Length: 320[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Host: api.rest.company.com[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "Connection: Keep-Alive[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "User-Agent: Apache-HttpClient/4.2.6 (java 1.5)[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "[\r][\n]"
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> POST /v1/jobs/docker HTTP/1.1
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Content-Type: application/json
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Authorization: Bearer correcttoken; Path=/; Domain=auth.server.com; Expires=Fri, 01 Jul 2016 17:51:08 UTC
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Content-Length: 320
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Host: api.rest.company.com
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> Connection: Keep-Alive
DEBUG [2016-06-30 17:51:08,666] org.apache.http.headers: >> User-Agent: Apache-HttpClient/4.2.6 (java 1.5)
DEBUG [2016-06-30 17:51:08,666] org.apache.http.wire: >> "{"correct Json Entity"}"
DEBUG [2016-06-30 17:51:08,667] org.apache.http.wire: << "HTTP/1.1 401 Unauthorized[\r][\n]"
DEBUG [2016-06-30 17:51:08,667] org.apache.http.wire: << "Server: nginx[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Date: Thu, 30 Jun 2016 17:51:08 GMT[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Content-Type: application/json[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Content-Length: 62[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Connection: keep-alive[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "Minimum-Apc-Version: 2.0.0[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.wire: << "[\r][\n]"
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.conn.DefaultClientConnection: Receiving response: HTTP/1.1 401 Unauthorized
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << HTTP/1.1 401 Unauthorized
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Server: nginx
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Date: Thu, 30 Jun 2016 17:51:08 GMT
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Content-Type: application/json
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Content-Length: 62
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Connection: keep-alive
DEBUG [2016-06-30 17:51:08,668] org.apache.http.headers: << Minimum-Apc-Version: 2.0.0
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: Connection can be kept alive indefinitely
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: Authentication required
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: api.rest.company:80 requested authentication
DEBUG [2016-06-30 17:51:08,668] org.apache.http.impl.client.DefaultHttpClient: Response contains no authentication challenges

是否可以与日志中的以下两行相关

DEBUG [2016-06-30 17:51:08,665] org.apache.http.client.protocol.RequestAuthCache: Auth cache not set in the context
DEBUG [2016-06-30 17:51:08,665] org.apache.http.client.protocol.RequestProxyAuthentication: Proxy auth state: UNCHALLENGED

可能是由nginx代理重定向后标头丢失了吗?

1 个答案:

答案 0 :(得分:0)

我想原因是您使用了post.addHeader。相反,您应该使用post.setHeader。从我的角度来看,代码应类似于以下内容

JSONObject json = new JSONObject();
json.put("image_url", "http://xx.xx");  // set the image_url parameter's value here
json.put("job_fqn", "xx");              // set the job_fqn parameter's value here
JSONArray routesJsonArray = new JSONArray();
routesJsonArray.put(0, "");
json.put("routes",routesJsonArray);

try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(API_URL);


        StringEntity params = new StringEntity(json.toString(), "UTF-8");
        httpPost.setHeader("Authorization", "Bearer " + authToken);
        httpPost.setHeader("Content-Type","application/json");
        httpPost.setEntity(params);

        final HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
        HttpConnectionParams.setSoTimeout(httpParams, 30000);
        httpPost.setParams(httpParams);

        LOGGER.debug("Request is being processed. HTTP Post: [" + EntityUtils.toString(httpPost.getEntity()) + "]");

        HttpResponse httpResponse = httpClient.execute(httpPost);

        String responseStr = EntityUtils.toString(httpResponse.getEntity());

        LOGGER.debug("Response String: " + responseStr);


        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            LOGGER.info("Request is successful!");
        } else {
            LOGGER.error("Request failed!");
            return -1;
        }
        return 0;
    } catch (ClientProtocolException cpe){
        LOGGER.error("ClientProtocolException while processing the request", cpe);
        return -1;
    }catch (SocketTimeoutException ste){
        LOGGER.error("SocketTimeoutException while processing the request", ste);
        return -1;
    }catch (IOException e){
        LOGGER.error("IOException while processing the request", e);
        return -1;
    }catch (Exception e){
        LOGGER.error("Exception while processing the request", e);
        return -1;
    }