curl命令如何转换为java命令



我需要把下面的curl命令转换成Java命令。

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

我写了下面的代码:

public static void main(String[] args) throws MalformedURLException, IOException{
HttpURLConnection con = (HttpURLConnection) new URL("https://api.linkedin.com/v2/me").openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Bearer xxx");
con.setDoOutput(true);
con.setDoInput(true);
con.getOutputStream().write("LOGIN".getBytes("UTF-8"));
con.getInputStream();
}

但是我得到一个错误:

Exception in thread "main" java.io.FileNotFoundException: https://api.linkedin.com/v2/me
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1915)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
at testiamo.main(testiamo.java:18)

我会选Apache HttpClient

并以这种方式执行调用:

CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("https://api.linkedin.com/v2/me");
postRequest.addHeader("Authorization", "Bearer xxx");
// You could also send something through JSON...
if(requestBody != null)
{
postRequest.addHeader("content-type", "application/json");
StringEntity jsonEntity = new StringEntity(requestBody);
postRequest.setEntity(jsonEntity);
}
// 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);
}

更多信息请点击这里。

最新更新