I'm using Java 7.
I'm trying to access the API(https) using authorization bearer token in Java.
Here is the client code that I used:
public class HttpURLConnectionExample {
public static void main(String[] args) throws Exception {
try {
URL url = new URL("https://example-url.com/xxx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer eyXXXXXX");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
// printing result from response
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Then I get the error response result:
javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path validation
failed: java.security.cert.CertPathValidatorException: timestamp check
failed
How to solve it?
The API you are using needs a secure connection to do that import the certificate for the api into your jre location using keytool command
Related
I am trying to retrieve users information from Azure active directory using Microsoft Graph api from java code but i am getting 400 error(Bad request) , but it works well in postman .
The java code with which i am working is
String url = "https://graph.microsoft.com/v1.0/users?$filter=displayName eq 'Dasari Siri'";
String token = "Bearer "+accesstoken;
URL obj = new URL(url);
HttpURLConnection con =(HttpURLConnection)obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", token);
con.connect();
StringBuffer Response = new StringBuffer();
if(con!=null){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String input ;
while ((input = br.readLine()) != null){
Response.append(input);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
The error which I am getting is
java.io.IOException: Server returned HTTP response code: 400 for URL: https://graph.microsoft.com/v1.0/users?$filter=displayName eq 'Dasari Siri'
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.javatpoint.Downloadcsv.doDownloadCsv(Downloadcsv.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
The postman request which worked fine for me is :
Can you please go through this and let me know where i am making mistake
Thank you in advance
You need to do the encode for the filter part of the url and add a line to set property "Accept" as "application/json"). Please refer to my code below:
public class Testgraph {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String url = "https://graph.microsoft.com/v1.0/users?" + URLEncoder.encode("$filter=displayName eq 'huryTest'", "UTF-8");
String token = "Bearer " + "your access token";
URL obj = new URL(url);
HttpURLConnection con =(HttpURLConnection)obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", token);
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
int responseCode = con.getResponseCode();
StringBuffer Response = new StringBuffer();
if(con!=null){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String input ;
while ((input = br.readLine()) != null){
Response.append(input);
System.out.print("---------success------");
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
I'm trying to access FCM from my server app. Checked the example provided into here! But getting error:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://fcm.googleapis.com/v1/projects/unsaarmdm/messages:send
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at asd.MessagesClientFCMServer.sendMessageToFcm(MessagesClientFCMServer.java:66)
at asd.MessagesClientFCMServer.sendData(MessagesClientFCMServer.java:40)
at asd.MessagesClientFCMServer.main(MessagesClientFCMServer.java:37)
I've already created the firebase project called "unsaarmdm" and downloaded the json file that contains the private key. Also added the Google API Client library into my project.
Below is the code snippets:
private static String FCM_DEALS_ENDPOINT
= "https://fcm.googleapis.com/v1/projects/unsaarmdm/messages:send";
//https://fcm.googleapis.com/v1/projects/unsaarmdm/messages:send
public static void main(String args[]) {
MessagesClientFCMServer fcmClient = new MessagesClientFCMServer();
fcmClient.sendData();
}
private void sendData(){
sendMessageToFcm(getFcmMessageJSONData());
}
//Using HttpURLConnection it send http post request containing data to FCM server
private void sendMessageToFcm(String postData) {
try {
HttpURLConnection httpConn = getConnection();
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(postData);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
log.info(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("C:/dev/Firebase_private_key/unsaarmdm-firebase-adminsdk.json"))
.createScoped(Arrays.asList(SCOPE));
googleCredential.refreshToken();
String token = googleCredential.getAccessToken();
return token;
}
//create HttpURLConnection setting Authorization token
//and Content-Type header
private HttpURLConnection getConnection() throws Exception {
URL url = new URL(FCM_DEALS_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
return httpURLConnection;
}
The url looks more like https://fcm.googleapis.com/fcm/send
This is a weird part, I'm aware the docs say to use the URL you are using, but I have a working implementation (and I know I spent some time debbuging this) with the URL i just mentioned, try and let me know :) we all can learn.
Make sure you include the server key into the Authorization header (which it seems you are doing ok).
I'm trying to connect to GDAX using their REST API.
I first want to do something very simple, i.e. getting historic rates.
I tried this:
private static final String GDAX_URL = "https://api.gdax.com";
public String getCandles(final String productId, final int granularity) {
HttpsURLConnection connection = null;
String path = "/products/" + productId + "/candles";
try {
//Create connection
URL url = new URL(GDAX_URL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("granularity", String.valueOf(granularity));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(path);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
But I get a 400 code in return "Bad Request – Invalid request format".
My problem is with the passing of the path "/products//candles" and the parameters (e.g. granularity).
I don't understand what should go in the request properties and in the message itself, and in what form.
I managed to make it work like this:
URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
Not sure how to use the DataOutputStream, so I just removed it. At least it works.
I'm getting this exception randomly when trying to make https request, sometimes it works and sometimes failed to make handshaking with this exception.
And I'm trying with lollipop and marshmallow.
javax.net.ssl.SSLProtocolException:
SSL handshake terminated: ssl=0x9d397c00: Failure in SSL library, usually a protocol error
error:100c543e:SSL routines:ssl3_read_bytes:TLSV1_ALERT_INAPPROPRIATE_FALLBACK (external/boringssl/src/ssl/s3_pkt.c:972 0x9b0bb3e0:0x00000001)
Here's how I'm making the requests
URL url;
HttpURLConnection connection;
try {
String serverUrl = "...";
url = new URL(serverUrl);
connection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.i(TAG, "OK");
Log.i(TAG, "response " + in.readLine());
} else {
Log.e(TAG, "Error " + responseCode);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
I try to send a json object to a distant server using HttpURLConnection.
but this error was displayed
"Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 401
at TestSendSMS.main(TestSendSMS.java:40)"
I didn't know what's the problem.What's wrong in this code? Any help
try {
/*
* JSONObject jsonParam = new JSONObject();
* jsonParam.put("-----","----"); jsonParam.put("----","-----");
* jsonParam.put("-----","-----");
*/
String input = "{\"------\":\"------\",\"-----\":\"------\",\"------\":\"-----\"}";
System.out.println("JsonObj " + jsonParam);
URL myURL = new URL("-----------------------");
HttpURLConnection myURLConnection = (HttpURLConnection) myURL
.openConnection();
myURLConnection.setDoOutput(true);
myURLConnection.setDoInput(true);
myURLConnection.setChunkedStreamingMode(0);
myURLConnection.setUseCaches(false);
myURLConnection.setConnectTimeout(10000);
myURLConnection.setReadTimeout(10000);
myURLConnection.setRequestProperty("Content-Type",
"application/json");
myURLConnection.setRequestProperty("Accept", "application/json");
OutputStream os = myURLConnection.getOutputStream();
os.write(input.getBytes());
os.flush();
if (myURLConnection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ myURLConnection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(myURLConnection.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
System.out.println("error1");
}
catch (IOException e) {
System.out.println("error2");
}
HTTP Error 401 is an authentication problem.
You need to authenticate to the server when sending the request.
This topic may help you authenticate with URLConnection :
How to handle HTTP authentication using HttpURLConnection?