简体   繁体   English

将cURL调用转换为Java

[英]Convert cURL call to Java

I have the following cURL that I want to convert to java code: 我有以下要转换为Java代码的cURL:

curl -i -b 'JSESSIONID=ekl23l2-3321-1930-b889-kelwek23b8v9; Path=/; HttpOnly' http://127.0.0.1:8080/api/library

In the above call, JSESSIONID cookie is responsible for making sure that the server authenticates the call. 在上述调用中,JSESSIONID cookie负责确保服务器对调用进行身份验证。 I came up with the following Java code: 我想出了以下Java代码:

    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();     

However, this doesn't work for me as the server complains of unauthorized access. 但是,这对我不起作用,因为服务器抱怨未经授权的访问。 This response happens when user is not authorized, which means that somehow the JSESSIONID is not getting properly setup. 当用户未获得授权时,就会发生此响应,这意味着JSESSIONID不能正确设置。 Can anyone comment if this is the proper way to translate the cURL to Java? 任何人都可以发表评论,如果这是将cURL转换为Java的正确方法?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM