cURL command to Java - 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());

Related

Getting an access token using OAuth, the response appears to be encoded

I'm pretty new to OAuth and am trying to refresh a token using a simple java client. Everything seems to go ok (or I think it does), the problem is I can't tell from the response if it's a good one. The http response code is 200, but when trying to parse the response for access_token, I get a null. Also difficult to troubleshoot is the "raw" response is garbled, or encoded in some way. I was thinking maybe it's byte but it doesn't seem to be. Here's the code:
private static String getClientCredentials() {
String postParams = "grant_type=refresh_token&refresh_token=1234567890";
Pattern pat = Pattern.compile(".*\"access_token\"\\s*:\\s*\"([^\"]+)\".*");
String clientId = "myClientID123";
String clientSecret = "myClientSecret123";
String tokenUrl = "https://www.host.com/oauth2/tenant/token";
String auth = clientId + ":" + clientSecret;
String authentication = Base64.getEncoder().encodeToString(auth.getBytes());
BufferedReader reader = null;
HttpsURLConnection connection = null;
String returnValue = "";
try {
URL url = new URL(tokenUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic " + authentication);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
connection.setRequestProperty("Connection", "keep-alive");
connection.setDoOutput(true);
OutputStream outStream = connection.getOutputStream();
outStream.write(postParams.getBytes());
outStream.flush();
outStream.close();
System.out.println("Resp code: " + connection.getResponseCode());
System.out.println("Resp message: " + connection.getResponseMessage());
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
StringWriter out = new StringWriter(connection.getContentLength() > 0 ? connection.getContentLength() : 2048);
while ((line = reader.readLine()) != null) {
out.append(line);
}
String response = out.toString();
Matcher matcher = pat.matcher(response);
if (matcher.matches() && matcher.groupCount() > 0) {
returnValue = matcher.group(1);
}
System.out.println("response: " + response);
System.out.println("returnValue: " + returnValue);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
connection.disconnect();
}
return returnValue;
}
Here's the console output, sorry, I had to screenshot it because the characters didn't paste right:
Response Screenshot
Am I trying something that isn't allowed or is there a way to decode the response so I can run the pattern match to extract only the access_token? Or am I going about it all wrong? Any help is greatly appreciated in advance!

How send GET request with value of parameter containing a space?

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

Convert curl to httpGet

I am looking to use the following curl request in a java code. I see that we can use httpget to call rest services.
Here is my curl command:
curl -XGET 'localhost:9200/indexname/status/_search' -d '{"_source": {"include": [ "field1", "name1" ]}, "query" : {"term": { "Date" :"2000-12-23T10:12:05" }}}'
How can I put that command in my HttpGet httpGetRequest = new HttpGet(....);
Please advice. Thanks.
You could use the HttpURLConnection.
This code is an example I think it will work for you:
public void get() throws IOException{
//Create a URL object.
String url = "localhost:9200/indexname/status/_search";
URL getURL = new URL(url);
//Establish a https connection with that URL.
HttpsURLConnection con = (HttpsURLConnection) getURL.openConnection();
//Select the request method, in this case GET.
con.setRequestMethod("GET");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
String parameters = "{\"_source\": {\"include\": [ \"field1\", \"name1\" ]}, \"query\" : {\"term\": { \"Date\" :\"2000-12-23T10:12:05\" }}}";
//Write the parameter into the Output Stream, flush the data and then close the stream.
wr.writeBytes(parameters);
wr.flush();
wr.close();
System.out.println("\nSending 'GET' request to URL : " + url);
int responseCode;
try {
responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
} catch (Exception e) {
System.out.println("Error: Connection problem.");
}
//Read the POST response.
InputStreamReader isr = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
//Save a line of the response.
response.append(inputLine + '\n');
}
br.close();
System.out.println(response.toString());
}
If that doesnt work it's because i must have misstyped the parameters, try it anyway
The combination -X GET and -d results in your data being appended to the URL in application/x-www-form-urlencoded format.
Therefore, I suggest using URLEncoder as follows:
String host = "localhost:9200/indexname/status/_search";
String data = "{\"_source\": {\"include\": [ \"field1\", \"name1\" ]}, \"query\" : {\"term\": { \"Date\" :\"2000-12-23T10:12:05\" }}}";
String url = host + "?" + URLEncoder.encode(data, "UTF-8");

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