【问题标题】:Apache HTTPClient unauthorizedApache HTTPClient 未经授权
【发布时间】:2021-10-09 09:46:03
【问题描述】:

我必须在 java 中编写这个 curl 命令的等效项(有效):

curl https://api.linkedin.com/v2/me -H "Authorization: Bearer xxx"

我正在使用此代码:


import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class testiamo {

    public static void main(String[] args) throws MalformedURLException, IOException{
        CloseableHttpClient client = HttpClientBuilder.create().build();

        HttpPost postRequest = new HttpPost("https://api.linkedin.com/v2/me");
        postRequest.addHeader("Authorization", "Bearer xxx");

        // Getting the response
        HttpResponse rawResponse = client.execute(postRequest);
        final int status = rawResponse.getStatusLine().getStatusCode();
        final StringBuilder response = new StringBuilder();

        // If status == 200 then we get the response (which could be JSON, XML and so on) and save it as a string.
        if(status == HttpStatus.SC_OK)
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    rawResponse.getEntity().getContent()));

            String inputLine;

            while ((inputLine = reader.readLine()) != null)
            {
                response.append(inputLine);
            }

            reader.close();
            client.close();
        }
        else
        {
            client.close();
            throw new RuntimeException("Error while doing call!\nStatus: "+ status);
        }


    }
}

但我收到此错误:

ago 04, 2021 10:30:17 AM org.apache.http.client.protocol.ResponseProcessCookies processCookies
WARNING: Invalid cookie header: "Set-Cookie: li_gc=MTswOzE2MjgwNjU4MTc7MjswMjFHaojFfu7ZrccbD2V9NU7pLUJlhg+my7cV7lmf3L/aRg==; Domain=.linkedin.com; Expires=Fri, 21 Jul 2023 00:02:44 GMT; Path=/; Secure; SameSite=None". Invalid 'expires' attribute: Fri, 21 Jul 2023 00:02:44 GMT
Exception in thread "main" java.lang.RuntimeException: Error while doing call!
Status: 401
    at testiamo.main(testiamo.java:47)

Process finished with exit code 1

【问题讨论】:

    标签: java curl


    【解决方案1】:

    试试这个:

    HttpPost postRequest = new HttpPost("https://api.linkedin.com/v2/me");
    
    postRequest.setHeader(HttpHeaders.CONTENT_TYPE,"application/json");
    postRequest.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + YOUR_TOKEN);
    

    然后尝试执行请求。

    我假设请求是 POST 请求。但如果不是这种情况,则使用相同的方式执行 GET 请求:

    CloseableHttpClient client= HttpClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.STANDARD).build())
            .build();
    HttpGet getRequest = new HttpGet(url);
    getRequest.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + YOUR_TOKEN);
    

    那么获取响应的步骤是一样的。

    更新

    检查API docs后,请求应该是GET请求。所以使用上面代码的第二个sn-p。

    祝你好运!

    【讨论】:

    • 我收到此错误:2021 年 4 月 4 日下午 12:09:25 org.apache.http.client.protocol.ResponseProcessCookies processCookies 警告:cookie 标头无效:“Set-Cookie: li_gc=MTswOzE2MjgwNzE3NjU7MjswMjEiBY4np8T9xEJYQizRbZiFizYA2Ra85YQizRbZiFiz =;Domain=.linkedin.com;Expires=Thu,2023 年 7 月 20 日 06:34:32 GMT;Path=/;Secure;SameSite=None”。无效的“过期”属性:2023 年 7 月 20 日星期四 06:34:32 GMT
    • 我更新了我的答案试试上面的实现
    【解决方案2】:

    Java 的 HTTP 客户端不能很好地处理 RFC 规范的 cookie。您可以像这样切换到标准规范:

    HttpClient client = HttpClientBuilder
       .create()
       .setDefaultRequestConfig(
          RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()
       )
       .build();
    

    【讨论】:

    • 我收到此错误:线程“main”中的异常 java.lang.RuntimeException:调用时出错!状态:testiamo.main(testiamo.java:59) 的 404 进程以退出代码 1 结束
    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多