How to convert a cURL call into a Java URLConnection call - java

I have a cURL command:
curl -d '{"mobile_number":"09178005343", "pin":"1111"}' -H "Content:Type: application/json" -H "X-Gateway-Auth:authentication" -X POST https://localhost:9999/api/traces/%2f/login
I need to create an HTTP Request in Java API which will do the same thing. I don't have any idea regarding this. Thank you in advance for those who will take time to respond.

There are multiple ways to do it. Firstly, since you want to send a JSON object, you might want to use a JSON library, for example, Google's gson. But to make it easy you can just send the request as a String. Here is a sample code that sends your JSON to your URL.
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("https://localhost:9999/api/traces/%2f/login");
StringEntity params =new StringEntity("{\"mobile_number\":\"09178005343\", \"pin\":\"1111\"");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//Do what you want with the response
}catch (Exception ex) {
//If exception occurs handle it
} finally {
//Close the connection
}

Related

How to send cURL -X POST --data-urlencode with Java

I've been looking all over the internet for this, and I just haven't found an answer that works. I'm trying to make a bukkit plugin that sends data to an ingoing Slack webhook when a command is run. I've gotten to noticing the command running, but I have no idea how to send the JSON. (For those of you unfamiliar with Slack, the command inside a terminal window is curl -X POST --data-urlencode 'payload={"channel":"#slack-channel-id","username":"bot's username","text":"Self explanatory","icon_emoji":"The bot's icon"}' https://slack.com/custom/webhook/token/here I've been looking all over and googling for a good hour trying to find a way in Java to send this. But no matter what I try it doesn't work. Any help is appreciated, thanks
//You can use the following code it works!
slackWebhook is the https endpoint for the channel that you can get from custom_integration link
String payload = "payload={\"channel\": \"#channel_name\", \"text\": \"This is posted "
+ "to #ewe_gps_abacus_notif and comes from a bot named change-alert.\"}";
StringEntity entity = new StringEntity(payload,
ContentType.APPLICATION_FORM_URLENCODED);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(slackWebhook);
request.setEntity(entity);
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response.getStatusLine().getStatusCode());

How to send POST request using HTTPURLConnection with JSON data

I have a RESTful API that I can call by doing the following:
curl -H "Content-Type: application/json" -d '{"url":"http://www.example.com"}' http://www.example.com/post
In Java, when I print out the received request data from the cURL, I correctly get the following data:
Log: Data grabbed for POST data: {"url":"http://www.example.com/url"}
But when I send a POST request via Java using HttpClient/HttpPost, I am getting poorly formatted data that does not allow me to grab the key-value from the JSON.
Log: Data grabbed for POST data: url=http%3A%2F%2Fwww.example.com%2Furl
In Java, I am doing this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/post/");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
BasicNameValuePair nvp1 = new BasicNameValuePair("url", "http://www.example.com/url);
nameValuePairs.add(nvp1);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpresponse = httpclient.execute(httppost);
How do I make it so that the request from Java is similar to cURL in terms of how the data is sent?
The data you present as coming from the Java client are URL-encoded. You appear to specifically request that by using a UrlEncodedFormEntity. It is not essential for the body of a POST request to be URL-encoded, so if you don't want that then use a more appropriate HttpEntity implementation.
In fact, if you want to convert generic name/value pairs to a JSON-format request body, as it seems you do, then you probably need either to use a JSON-specific HttpEntity implementation or to use a plainer implementation that allows you to format the body directly.

Sending JSON in GET Rest resource - curl and code have separate behavior

I will start with: I am doing something terribly wrong. And here is what I am doing wrong.
I created a REST resource for searching something and I am expecting a JSON data in request parameters:
#GET
#Path("/device")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response searchContent(String searchJSONString) {
String message = new SearchServices().search(searchJSONString);
return getResponse(message); //Checks the message for any error and sends back the response.
}//end of searchContent()
I should not have written:
#Consumes
since it is a GET resource and it does not consumes anything. But my problem is how to send JSON data in a java code for this (GET resource). I tried curl command which is able to send JSON data to this resource but not a java code by any means.
I tried following curl command to send JSON data to it:
curl -X GET -H "Content-Type: application/json" -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search
And its working fine and giving me back a proper JSON response.
But if I am using a curl command without specifying any method (which should be a default http get), I am getting a 405 (Method not allowed) response from tomcat:
curl -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search
or through Java code:
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("GET"); //This is not working.
getting the same 405 (Method not allowed) response from tomcat.
If I am sending a GET request using java code, I am not able to send the JSON data as in a post method, and I am forced to use a name=value thing and for that I need to change my REST resource to accept it as a name/value pair.
It means something like this:
http://localhost:8080/search-test/rest/search?param={"keyword":"permission"}
If I am doing something similar in POST:
#POST
#Path("/device")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response searchContent(String searchJSONString) {
String message = new SearchServices().search(searchJSONString);
return getResponse(message); //Checks the message for any error and sends back the response.
}//end of searchContent()
I am able to send the JSON data both from Java code and curl command as well:
curl -X POST -H "Content-Type: application/json" -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search
or through Java code:
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
urlConnection.setRequestMethod("POST"); //Works fine.
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoOutput(true);
Where is the problem? Why am I not able to send it from code but from curl? Is there any other way to send JSON data to the GET resource other than a name=value pair?
HttpURLConnection does not allow GET requests with entity and will strip the entity from the request before it is sent to the server. So, I'd strongly recommend avoiding it as even if you use a different Java HTTP client library that allows you to do it, your users will likely run into similar issues (plus web caches and proxies may add more problems).

translating curl command into java/android

Can someone help me figure out how to translate the following curl commands into Java syntax for use in an Android application?
The curl commands are:
curl -u username:password -H "Content-Type:application/vnd.org.snia.cdmi.container" http://localhost:8080/user
curl -u username:password -T /home/user1/a.jpg -H "Content-Type:image" http://localhost:8080/user/a.jpg
thanks
You can use Apache HttpClient in Android for performing HTTP posts.
HttpClient code snippet (untested)
public void postData(String url) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Set the headers (your -H options)
httpost.setHeader("Content-type", "application/json");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("param1", "value1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
// Exception handling
}
}
Check the following link for the basic authentication part (your -u option)
http://dlinsin.blogspot.com/2009/08/http-basic-authentication-with-android.html
Check the following answer for your file upload (your -T option)
How to upload a file using Java HttpClient library working with PHP

How to add json to the body of an http post in java

I'm trying to post some JSON data in java for an Android app I'm working on. Is the below valid or do I need to push the JSON string in a different way?
HttpPost httpost = new HttpPost("http://test.localhost");
httpost.setEntity(new StringEntity("{\"filters\":true}"));
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
//... other java code to execute the apache httpclient
Thank you in advance
You should set the Content-Type header to "application/json". Everything else looks good.

Categories