【发布时间】: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
【问题讨论】: