How to get Token with java - java

I'am new in JWT so i need to get a token with JAVA code from a webService (GET Method).
In postMan i was able to get the token (below the screenshot).
I used this java code but this return often Response Code : 403
String url = "https://WEBSERVICE_LINK";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
this.log.info("Sending 'GET' request to URL : " + url);
con.setRequestProperty("Authorization", Base64.getEncoder().encodeToString((username + ":" + pwd).getBytes()));
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
this.log.info("Response Code : " + responseCode);
StringBuilder response;
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
String reponseString = response.toString();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(reponseString);
// Isoler et transmettre le Token
this.token = jsonNode.get("token") != null ? jsonNode.get("token").asText() : null;
this.log.info("Token : " + this.token);
Thank you

You seem to have forgotten the Basic prefix in the Authorization header value:
con.setRequestProperty(
"Authorization",
"Basic " + Base64.getEncoder().encodeToString((username + ":" + pwd).getBytes())
);

Related

How to read JSON Object on the second array with Java/JavaFX code

I am trying to read JSON data with Java, I was successfully to read the first array, below is my JSON report from url.
{
"success":1,
"object":"sale",
"id":"sl987575",
"created":"2019-08-03 21:40:35",
"product_id":"prd00123",
"product_name":"AirBuss",
"amount":"100.00",
"currency":"USD",
"status":"Completed",
"meta":[],
"customer":{
"object":"customer",
"id":"001234",
"email":"someone#email.com",
"name":"Full Name",
"country":null,
"firstname":"Full",
"lastname":"Name"}}
I can read "product_name" and "status" but cannot read the "email" data.
public static void call_me() throws Exception {
String url = "Link WEbsite/api/?apiKey=23459876";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print in String
System.out.println(response.toString());
//Read JSON response and print
JSONObject myResponse = new JSONObject(response.toString());
System.out.println("result after Reading JSON Response");
System.out.println("Product Name : "+myResponse.getString("product_id"));
System.out.println("status : "+myResponse.getString("status"));
System.out.println("Email : "+myResponse.getString("email"));
}
Try this:
System.out.println("Email : " + myResponse.getJSONObject("customer").getString("email"));
Because 'email', 'country' etc. fields in a nested object named customer.
I just found solution for my own question..
JSONObject customer_data = myResponse.getJSONObject("customer");
System.out.println("Email : "+customer_data.getString("email"));

Geocode API is returning null in HTTP response

I am trying to get coordinates from a location entered from the user using HTTP request to Geocode API.
The address string I pass into the method is formatted with "%" in between the spaces so that it can be put into a URL.
Sometimes, it will return a null value and I have no idea why.
It works sometimes so I think there isn't a problem with the JSON array get lines.
public CheckLocation(String address) {
try {
String key = "insert key";
String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "?key=" + key;
// String key = "test/";
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Read JSON response and print
JSONObject myResponse = new JSONObject(response.toString());
double laditude = ((JSONArray)myResponse.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
double longitude = ((JSONArray)myResponse.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
formattedAddress = ((JSONArray)myResponse.get("results")).getJSONObject(0)
.getString("formatted_address");
coordinates = (laditude + "," + longitude);
}
catch (Exception e) {
e.printStackTrace();
}
}
What about encoding parameters values? encode both address and key:
String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" +
URLEncoder.encode(address, "UTF-8"); + "?key=" + URLEncoder.encode(key, "UTF-8");
URLEncoder should be the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value

Getting HTML response instead of Json response

I'm getting HTML response instead of JSON response. I'm using following code and I'm receiving HTML response as bf.readLine(). Is there any issue in following code or is this API issue?
String uri = "http://192.168.77.6/Ivr_ABN_API/?id=" + mobile;
URL url;
Gson json = null;
try {
url = new URL(uri);
json = new Gson();
HttpURLConnection connection;
access_token = db.getAccessTokenFromDB();
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
System.out.println("URL:" + uri);
connection.setRequestProperty("Content-Type", "application/json");
int status = connection.getResponseCode();
resCode = Integer.toString(status);
System.out.println("status is " + status);
InputStream in = connection.getInputStream();
System.out.println("inputStreamer " + in);
BufferedReader bf = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
System.out.println("bf.readLine() - " + bf.readLine());
while ((output = bf.readLine()) != null) {
JSONObject obj = new JSONObject(output);
System.out.println("output is " + output);
resCode = obj.getString("resCode");
resDesc = obj.getString("COUNT");
}
Perhaps try sending the header Accept: application/json
If that doesn't work, then review the documentation for the API and see if there's something else you should be sending to return json.
For java
Set The Request Property as the following:
con.setRequestProperty("Accept","application/json")
It will solve the issue you are facing.

Why Google Recaptcha returns false after a specific time in java?

I am using Google reCAPTCHA in my project. It works fine. But after a specific time, my code is returning the response value is false. It should be true.
Not always like this, but after 10 days(for example) returning false.I am not hitting any daily usage limit.
The problem is solving when I restart the server (apache tomcat).
My code is:
public static boolean verify(String gRecaptchaResponse) throws IOException {
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
return false;
}
try {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String postParams = "secret=" + secret + "&response="
+ gRecaptchaResponse;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
//parse JSON response and return 'success' value
JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
return **jsonObject.getBoolean("success");**
} catch(Exception e){
e.printStackTrace();
return false;
}
}

HTTP response code 400 sending GET Request to HTTPS Query API

I'm trying to send email using the SES HTTPS Query API. I have a java method that sends a GET request to an Amazon SES endpoint, I'm trying to send an email with SES and capture the result.
Code:
public static String SendElasticEmail(String timeConv,String action,String source, String destinationAddr, String subject, String body) {
try {
System.out.println("date : "+timeConv);
System.out.println("In Sending Mail Method......!!!!!");
//Construct the data
String data = "Action=" + URLEncoder.encode(action, "UTF-8");
data += "&Source=" + URLEncoder.encode(source, "UTF-8");
data += "&Destination.ToAddresses.member.1=" + URLEncoder.encode(destinationAddr, "UTF-8");
data += "&Message.Subject.Data=" + URLEncoder.encode(subject, "UTF-8");
data += "&Message.Body.Text.Data=" + URLEncoder.encode(body, "UTF-8");
//Send data
System.out.println("https://email.us-east-1.amazonaws.com?"+data);
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
//URLConnection conn = url.openConnection();
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("x-amz-date" , timeConv);
con.setRequestProperty("Content-Length", ""+data.toString().length());
con.setRequestProperty("X-Amzn-Authorization" , authHeader);
int responseCode = ((HttpsURLConnection) con).getResponseCode();
String responseMessage = ((HttpsURLConnection) con).getResponseMessage();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
//System.out.println("Response Message : " + responseMessage);
InputStream stream = con.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
System.out.println("hgfhfhfhgfgfghfgh");
BufferedReader br = new BufferedReader(isReader);
String result = "";
String line;
while ((line = br.readLine()) != null) {
result+= line;
}
System.out.println(result);
br.close();
con.disconnect();
}
catch(Exception e) {
e.printStackTrace();
}
return subject;
}
I have calculated the signature correctly, because on hitting from postman client getting 200 response.
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
You missed a '/' before the question mark. It should be
URL url = new URL("https://email.us-east-1.amazonaws.com/?"+data);

Categories

Resources