HTTP response code 400 sending GET Request to HTTPS Query API - java

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);

Related

How to get Token with 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())
);

Microsoft IdentityModel Tokens AudienceUriValidationFailedException when trying to access Sharepoint using REST API

I am struggling to understand the whole new idea of accessing my organizatioon's Sharepoint content using Sahrepoint REST API and I am trying to implementing it in java. My aim is to read all the files in "abc" folder which is in Documents folder. Steps I did.
Register the app:
Click Generate Client ID,
Click Generate Client Secret,
Gave Title,
Gave Appdomain as companyname.onmicrosoft, and
Gave Request URI as https://companyname.sharepoint.com/Shared%20Documents/Forms/AllItems.aspx
Got the app registered. I have client id, client secret, and tenant id.
I used the below code to generate the access token
public String getSpToken(String shp_clientId, String shp_tenantId, String shp_clientSecret) {
String accessToken = "";
try {
// AccessToken url
String wsURL = "https://accounts.accesscontrol.windows.net/" + shp_tenantId + "/tokens/OAuth/2";
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
// Set header
httpConn.setRequestProperty("Content-Type", " ");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
// Prepare RequestData
String jsonParam = "grant_type=client_credentials"
+ "&client_id=" + shp_clientId + "#" + shp_tenantId
+ "&client_secret=" + shp_clientSecret
+ "&resource=00000003-0000-0ff1-ce00-000000000000/www.companyname.sharepoint.com#" + shp_tenantId;
// Send Request
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(jsonParam);
wr.flush();
wr.close();
// Read the response.
InputStreamReader isr = null;
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
} else {
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
String responseString = "";
String outputString = "";
// Write response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
//Printing the response to the console
System.out.println("Output from the REST" + outputString);
// Extracting accessToken from string, here response (outputString)is a Json format string
if (outputString.indexOf("access_token\":\"") > -1) {
int i1 = outputString.indexOf("access_token\":\"");
String str1 = outputString.substring(i1 + 15);
int i2 = str1.indexOf("\"}");
String str2 = str1.substring(0, i2);
accessToken = str2;
}
//Printing the access token
System.out.println("Access token is " + accessToken);
} catch (Exception e) {
accessToken = "Error: " + e.getMessage();
}
return accessToken;
}
Now that I have the access token in the String variable "accessToken", I used the following code to read the filenames inside the folder "abc" in Documents folder using readFiles() method
public void readFiles(String accessToken) {
try {
//Frame SharePoint siteURL
String siteURL = "https://companyname.sharepoint.com";
//Frame SharePoint URL to retrieve the name of all of the files in a folder
String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents/abc')/Files";
//Create HttpURLConnection
URL url = new URL(wsUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
//Set Header
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
httpConn.setRequestProperty("accept", "application/json;odata=verbose"); //To get response in JSON
//httpConn.setRequestProperty("AllowAppOnlyPolicy", "true");
//httpConn.setRequestProperty("Scope", "http://sharepoint/content/sitecollection/web\" Right=\"FullControl");
//Read the response
String httpResponseStr = "";
InputStreamReader isr = null;
System.out.println(httpConn.getResponseCode());
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
} else {
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
String strLine = "";
while ((strLine = in.readLine()) != null) {
httpResponseStr = httpResponseStr + strLine;
}
//Print response
System.out.println(httpResponseStr);
} catch (Exception e) {
System.out.println("Error while reading file: " + e.getMessage());
}
}
}
When I execute the above code I am getting {"error_description":"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}. Could someone please help me to figure out what I am doing wrong? I have been sitting on this for days and not able to resolve it.
Please help!

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.

cURL command to Java

I have a cURL command I want to translate in Java
curl -H "Key: XXX" -d url=http://www.google.com http://myapi.com/v2/extraction?format=json
It works fine.
I started to do in Java: (CODE EDITED, it works)
try {
// POST
System.out.println("POSTING");
URL url = new URL("http://myapi.com/v2/extraction?format=json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Key", "XXX");
String data = "http://www.google.com";
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("url=" +data);
writer.close();
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + data);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("REPOSNE" +response.toString());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
But I don't know how to set my arguments.
Thanks for your help.
Jean
If you mean to set a header field Key with value XXX you can use the setRequestProperty
ie
conn.setRequestProperty("Key", "XXX");
If you want to send data, use
String data = "url=http://www.google.com";
conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
EDIT:-
For posting data as form url encoded, try the following code
String data = "url=" + URLEncoder.encode("http://www.google.com", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
wr.write(data.getBytes());

Categories

Resources