将cURL调用转换为Java

时间:2017-01-26 08:13:18

标签: java rest curl get httpclient

我有以下要转换为java代码的cURL:

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/api/library");
    httpGet.addHeader("Set-Cookie","JSESSIONID=ekl23l2-3321-1930-b889-kelwek23b8v9; Path=/; HttpOnly");
    HttpResponse httpResponse = httpClient.execute(httpGet);
    BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    JSONObject o = new JSONObject(result.toString());
    rd.close();
    httpClient.close();     

在上面的调用中,JSESSIONID cookie负责确保服务器验证调用。我提出了以下Java代码:

Add

然而,这并不适用于我,因为服务器抱怨未经授权的访问。当用户未获得授权时会发生此响应,这意味着JSESSIONID无法正确设置。任何人都可以评论,如果这是将cURL翻译成Java的正确方法吗?

1 个答案:

答案 0 :(得分:2)

您正在使用Set-Cookie(来自响应标头中的服务器),而它应该只是Cookie:(来自请求标头中的客户端)。

httpGet.addHeader("Cookie","JSESSIONID=ekl23l2-3321-1930-b889-kelwek23b8v9; Path=/; HttpOnly");