How to send POST request using HTTPURLConnection with JSON data - java

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.

Related

How to convert a cURL call into a Java URLConnection call

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
}

read url content WHILE it is continuously updating

I have a php script that makes a few api calls in a row and once an api call has
returned data the script outputs the content. Meaning if you call the script on
the browser you will wait 1 second then see some content appear, than after 2 seconds
more content will be appended to the page and so on.
The thing is I am accessing this content from java/android in one of my apps.
Is there a way I can read this content from java WHILE it is updating? This
way I will populate the application content as new data is being fetched from
the script.
I have tried something like this when I have accessed xml files but they
were not continuously updating.
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
}
Yes, use URLConnection instead of HttpClient. Here's a tutorial.
Like in the tutorial, connection.getInputStream() will return a stream you can read and process, for example line-wise.

How to send strings to server using Java?

I need to send a lot of strings to a web server using Java.
I have a List<String> with huge amount of strings and I need to send it via POST request to the Struts2 action on the server side.
I have tried something starting with
HttpPost httppost = new HttpPost(urlStr);
but don't know how to use it.
On other side I have a Struts2 action, and getting the POST request is easy to me.
I think this solution is too close, but it doesn't solve my problem because it's using just one string :
HTTP POST using JSON in Java
So, how to send many strings to a server using Java?
You should do somthing
HttpPost httppost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<>();
for(String s : list)
params.add(new BasicNameValuePair("param", s));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
on the other side is an action mapped to the url has setter for param. It should be
List<String> or String[]. The action when intercepted will populate that param property.

Send Post request with raw data, and get a file

I have a POST method in the server side, which get a JSON (as raw text) and some headers. The response is data (a file content), which send by the server to the client.
I search for a way to write the client in Java. The client sends a POST message with raw text, and some headers, and know to get the response.
All the example I saw use the HttpsURLConnection, but I didn't see any way to send the raw text (JSON), and get the data content.
Perhaps something like this could help ?
(Using org.apache.httpcomponents:httpcore:4.3.2)
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("query", new InputStreamBody(rawData, "rawData.xml"))
.build();
HttpPost httppost = new HttpPost(serverUrl);
httppost.addHeader("SomeHeader", "SomeValue");
httppost.setEntity(reqEntity);
HttpClient httpclient = HttpClientBuilder.create().build();
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
InputStream os = response.getEntity().getContent();
...

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