I'm testing this code below to send GET request with parameters and this code fails when the value of parameter is a string containing a space, Ex: http://company.com/example.php?value=Jhon 123. Already if i send Jhon123 (withou any space) works fine.
Why this happens?
private static void sendGet(String site, String params) throws Exception {
site += params;
URL obj = new URL(site);
try {
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + site);
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());
} catch (Exception ex) {
}
}
You should URL Encode your request.
You can use URLEncoder to encode your parameter:
String url = "http://company.com/example.php?value=" + URLEncoder.encode("Jhon 123", "utf-8");
Related
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"));
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
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;
}
}
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);
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());