I would like to make a simple HTTP POST using JSON in Java.
Let's say the URL is www.site.com
and it takes in the value {"name":"myname","age":"20"} labeled as 'details' for example.
How would I go about creating the syntax for the POST?
I also can't seem to find a POST method in the JSON Javadocs.
Here is what you need to do:
Get the Apache HttpClient, this would enable you to make the required request
Create an HttpPost request with it and add the header application/x-www-form-urlencoded
Create a StringEntity that you will pass JSON to it
Execute the call
The code roughly looks like (you will still need to debug it and make it work):
// #Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
// #Deprecated httpClient.getConnectionManager().shutdown();
}
You can make use of Gson library to convert your java classes to JSON objects.
Create a pojo class for variables you want to send
as per above Example
{"name":"myname","age":"20"}
becomes
class pojo1
{
String name;
String age;
//generate setter and getters
}
once you set the variables in pojo1 class you can send that using the following code
String postUrl = "www.site.com";// put in your url
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
and these are the imports
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
and for GSON
import com.google.gson.Gson;
#momo's answer for Apache HttpClient, version 4.3.1 or later. I'm using JSON-Java to build my JSON object:
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
It's probably easiest to use HttpURLConnection.
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
You'll use JSONObject or whatever to construct your JSON, but not to handle the network; you need to serialize it and then pass it to an HttpURLConnection to POST.
protected void sendJson(final String play, final String prop) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the childThread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://192.168.0.44:80");
json.put("play", play);
json.put("Properties", prop);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch (Exception e) {
e.printStackTrace();
showMessage("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
Try this code:
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
}catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
I found this question looking for solution about how to send post request from java client to Google Endpoints. Above answers, very likely correct, but not work in case of Google Endpoints.
Solution for Google Endpoints.
Request body must contains only JSON string, not name=value pair.
Content type header must be set to "application/json".
post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
"{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
public static void post(String url, String json ) throws Exception{
String charset = "UTF-8";
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(json.getBytes(charset));
}
InputStream response = connection.getInputStream();
}
It sure can be done using HttpClient as well.
You can use the following code with Apache HTTP:
String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
response = client.execute(request);
Additionally you can create a json object and put in fields into the object like this
HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
For Java 11 you can use the new HTTP client:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost/api"))
.header("Content-Type", "application/json")
.POST(ofInputStream(() -> getClass().getResourceAsStream(
"/some-data.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
You can use publishers from InputStream, String, File. Converting JSON to a String or IS can be done with Jackson.
Java 11 standardization of HTTP client API that implements HTTP/2 and Web Socket, and can be found at java.net.HTTP.*:
String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("www.site.com"))
.header("content-type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
Java 8 with apache httpClient 4
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("www.site.com");
String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";
try {
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
// set your POST request headers to accept json contents
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
// your closeablehttp response
CloseableHttpResponse response = client.execute(httpPost);
// print your status code from the response
System.out.println(response.getStatusLine().getStatusCode());
// take the response body as a json formatted string
String responseJSON = EntityUtils.toString(response.getEntity());
// convert/parse the json formatted string to a json object
JSONObject jobj = new JSONObject(responseJSON);
//print your response body that formatted into json
System.out.println(jobj);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
I recomend http-request built on apache http api.
HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();
public void send(){
ResponseHandler<String> responseHandler = httpRequest.execute("details", yourJsonData);
int statusCode = responseHandler.getStatusCode();
String responseContent = responseHandler.orElse(null); // returns Content from response. If content isn't present returns null.
}
If you want send JSON as request body you can:
ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);
I higly recomend read documentation before use.
I'm using Java to send http requests to my API which is created using Laravel (5.4). If I send a request without any special characters it all works like a charm. But if there are any 'special' characters like: é, å, ö and such the request in Laravel is empty:
dd(request()->all()) outputs []
I guess this has to do with some wrong settings while creating the request in Java. I couldn't find a solution.
Here is the code responsible for creating the request.
public class HttpClient {
org.apache.http.client.HttpClient client;
public HttpClient() {
client = HttpClientBuilder.create().build();
}
public void post(String json) {
try {
HttpPost request = buildPostRequest(json);
HttpResponse response = createClient().execute(request);
int code = getStatusCode(response);
if (code != 200) {
throw new Exception("Error (" + code + ") on server.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private org.apache.http.client.HttpClient createClient() {
return HttpClientBuilder.create().build();
}
private HttpPost buildPostRequest(String json) throws Exception {
HttpPost request = new HttpPost("some uri");
request.addHeader("Content-type", "application/json; charset=utf-8");
request.addHeader("Accept", "application/json");
StringEntity params = new StringEntity(json);
params.setContentEncoding("utf-8");
params.setContentType("application/json; charset=utf-8");
request.setEntity(params);
return request;
}
private int getStatusCode(HttpResponse response) {
StatusLine line = response.getStatusLine();
return line.getStatusCode();
}
}
EDIT
Dump of the request before it get's send to the API.
I found a solution to the problem. In the buildPostRequest() method I changed from a StringEntity to a ByteArrayEntity and coverted the string to UTF-8 bytes.
ByteArrayEntity params = new ByteArrayEntity(json.getBytes("UTF-8"));
If I send special characters to the API the request isn't empty anymore.
try this way
HttpPost request = new HttpPost(URLEncoder.encode("url here", "UTF-8"));
I am trying to write a simple HttpClient program.
This is the first time I am working with HttpClient, I am quite confused which jars to include.
I have included the apache-httpcomponents-httpclient.jar and org.apache.commons.httpclient.jar with these ones when I create a HttpClient object I see different methods in the client object
package com.comverse.rht;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
public class HttpClientTest {
public static void main(String[] args) throws URIException {
URI url = new URI("http://www.google.com/search?q=httpClient");
HttpClient client = new HttpClient();
GetMethod get = new GetMethod();
PostMethod post = new PostMethod();
String responseString;
StringBuilder sb = new StringBuilder();
String line;
// add request header
get.setURI(url);
get.addRequestHeader("User-Agent", "shaiksha429");
try {
int respCode = client.executeMethod(get);
System.out.println("Response Code:" +respCode);
System.out.println(
"PCRF HTTP Status" + HttpStatus.getStatusText(respCode)
);
responseString = get.getResponseBodyAsString();
BufferedReader rd = null;
rd = new BufferedReader(
new InputStreamReader(get.getResponseBodyAsStream())
);
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println(sb);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But when I google I see a different example as below. What is the difference between the two? Why one HttpClient has "execute" and the other has "executeMethod". Which one I need to use?
String url = "http://www.google.com/search?q=httpClient";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent())
);
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
There were a lot of changes from HttpClient version 3 to version 4. The second example is definitely from HttpClient 4, so the first example is probably from the previous version.
Here is code that will do your google search, and read the result into a string
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(60);
connectionManager.setDefaultMaxPerRoute(6);
try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(connectionManager).build()) {
HttpGet request = new HttpGet("http://www.google.com/search?q=httpClient");
request.setHeader("User-Agent", "HttpClient");
try (CloseableHttpResponse response = client.execute(request)) {
MediaType mediaType = MediaType.parseMediaType(response.getFirstHeader("Content-Type").getValue());
Charset charSet = mediaType.getCharSet();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String body = CharStreams.toString(new InputStreamReader(is, charSet));
System.out.println("body = " + body);
EntityUtils.consume(entity);
}
}
First, you probably want to create a connection pool, so you can reuse the connection if you send multiple requests to the same server. The pool is typically created during application initialisation , for instance as a Spring singleton bean.
Here I used the ClosableHttpClient because it works with resource-try syntax, and you need to close both the httpClient, the response and the inputStream when you are done reading. The HttpClient is actually a lightweight object, the state like socket connection and cookies are stored elsewhere.
I use Spring's MediaType.parseMediaType() to get the char encoding, and Guavas CharStreams to convert the inputStream to a String. In my case google encoded the content using latin-1, because "search" is "søgning" in Danish.
The last step is to use EntityUtils.consume(entity), to ensure that all entity data has been read. If you use connection pooling this is important, because unread data will cause the connection to be thrown away, instead of being reused by the connection manager (this is extremely important if you are using https).
You're using a library whose interface has changed across its major versions. You can't casually copy jars and copy/paste examples without understanding which release you're using and which release an example or snippet was from.
Look at the examples that accompany the latest release and take anything old with a grain of salt.
Apache seems to move especially fast.
I have to write a code that retrieves specific information (not all of it) from url.com/info/{CODE} and uses json to display it in a server I have up.
This is my code up until now:
A class to get the info
#RequestMapping("/info")
public class Controller {
public void httpGET() throws ClientProtocolException, IOException {
String url = "Getfromhere.com/";
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = client.execute(request);
}
and a class that should return the data depending on the code inserted in the url by the user
#RequestMapping(value = "/{iataCode}", method = RequestMethod.GET)
#ResponseBody
public CloseableHttpResponse generate(#PathVariable String iataCode) {
;
return response;
}
How I can implement json for the return?.
To begin with, you must configure Spring to use Jackson or some other API to convert all your responses to json.
If the data you are retrieving is already in json format, you can return it as String.
Your big mistake: right now you are returning an object of type CloseableHttpResponse. Change return type of generate() from CloseableHttpResponse to String and return a string.
CloseableHttpResponse response = client.execute(request);
String res = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
byte[] bytes = IOUtils.toByteArray(instream);
res = new String(bytes, "UTF-8");
instream.close();
}
return res;
I am trying to write a small class using the Apache HttpClient library that would do an HTTPS post to a specified URL sending some XML. When I run my code, the HTTP status line I receive back is "403 Service Error". Here's the complete error HTML returned:
$errorDump java.net.SocketTimeoutException:Read timed out
$errorInfo
$errorDump java.net.SocketTimeoutException:Read timed out
$error Read timed out
$localizedError Read timed out
$errorType java.net.SocketTimeoutException
$user
$time 2011-10-25 09:39:29 EDT
$error Read timed out
$errorType java.net.SocketTimeoutException
This is the code I am using:
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HttpXmlPost {
public static void main(String[] args)
{
String url = "https://someurlhere.com";
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xmlTag></xmlTag>";
String content = request(xmlStr, url);
System.out.println(content);
}
private static String request(String xmlStr, String url) {
boolean success = false;
String content = "";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(url.trim());
InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(xmlStr.getBytes() ), -1);
reqEntity.setContentType("application/xml");
reqEntity.setChunked(true);
httpPost.setEntity(reqEntity);
System.out.println("Executing request " + httpPost.getRequestLine());
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if(response.getStatusLine().getStatusCode() == 200){
success = true;
}
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent()));
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf ))) {
buf.append( cbuf, 0, num );
}
content = buf.toString();
EntityUtils.consume(resEntity);
}
catch (Exception e) {
System.out.println(e);
}
finally {
httpclient.getConnectionManager().shutdown();
}
return content;
}
}
Whatever XML I pass in doesn't seem to matter, it gives the same error no matter what. Note that this actually works with some URLs. For example, if I put https://www.facebook.com, it goes through. However, it doesn't work for my specified URL. I thought it might be a certificate issue, tried to add some code to trust any certificate, didn't seem to work either, though I may have done it wrong. Any help is appreciated.
Based on the SocketTimeoutException in the first line of the response HTML, I'm guessing that the component which implements the handler for the URL to which you are posting is having some connection problems to a source system it needs to generate the response data.
Basically, it looks like the problem is on the server, not your client.