Reputation: 26567
i need to convert the following curl command into java command.
curl https://api.linkedin.com/v2/me -H "Authorization: Bearer xxx"
I writed this code:
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();
}
but I get an error:
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)
Upvotes: 0
Views: 69
Reputation: 4700
I would go with Apache HttpClient
And perform the call this way:
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);
}
For more info, click here.
Upvotes: 1