Java post request with json body

HTTP POST using JSON in Java

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.

12 Answers 12

Here is what you need to do:

  1. Get the Apache HttpClient , this would enable you to make the required request
  2. Create an HttpPost request with it and add the header application/x-www-form-urlencoded
  3. Create a StringEntity that you will pass JSON to it
  4. 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="); 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 could but it always good practice to abstract it out as JSONObject as if you are doing directly in the string, you might program the string wrongly and causing syntax error. By using JSONObject you make sure that your serialization is always follow the right JSON structure

In principal, they are both just transmitting data. The only difference is how you process it in the server. If you have only few key-value pair then a normal POST parameter with key1=value1, key2=value2, etc is probably enough, but once your data is more complex and especially containing complex structure (nested object, arrays) you would want to start consider using JSON. Sending complex structure using a key-value pair would be very nasty and difficult to parse on the server (you could try and you’ll see it right away). Still remember the day when we had to do that urgh.. it wasn’t pretty..

Читайте также:  Systemd service python script

Glad to help! If this is what you are looking for, you should accept the answer so other people with similar questions have good lead to their questions. You can use the check mark on the answer. Let me know if you have further questions

Shouldn’t the content-type be ‘application/json’. ‘application/x-www-form-urlencoded’ implies the string will be formatted similar to a query string. NM I see what you did, you put the json blob as a value of a property.

The deprecated part should be replaced by using CloseableHttpClient which gives you a .close() — method. See stackoverflow.com/a/20713689/1484047

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

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; 

Yes that is an Interface. You can create an instance using ‘HttpClient httpClient = new DefaultHttpClient();’

I find it slightly cleaner to use the ContentType parameter on StringUtils constructor and pass in ContentType.APPLICATION_JSON instead of manually setting the header.

@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

Do we have to add content-type explicitly? will the below work? entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, «application/json»)); Asking as it is not working for me. Using httpclient-4.5.1.jar.

@DarshanGopalR Yours seems to be a different way of using it. I wrote this answer 8 years ago, and didn’t test newer versions of httpclient . What I would try is to stick to the example the best as you can. I can give a try in a fresh project and update the answer if necessary.

Content type should be added e.g StringEntity entity = new StringEntity(params.toString(), ContentType.APPLICATION_JSON);

It’s probably easiest to use HttpURLConnection.

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.

JSONObject j = new JSONObject(); j.put(«name», «myname»); j.put(«age», «20»); Like that? How do I serialize it?

That’s true, this connection is blocking. This probably isn’t a big deal if you are sending a POST; it is much more important if you running a webserver.

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

Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it’s working) usually won’t help the OP to understand their problem

HttpClient httpClient = new DefaultHttpClient(); try < HttpPost request = new HttpPost("http://yoururl"); StringEntity params =new StringEntity("details="); 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

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.

  1. Request body must contains only JSON string, not name=value pair.
  2. Content type header must be set to «application/json».
post("http://localhost:8888/_ah/api/langapi/v1/createLanguage", ""); 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 mt24"> 
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
)">edited Apr 9, 2020 at 5:17
Enginer
3,018 1 gold badge 25 silver badges 22 bronze badges
answered Jun 13, 2015 at 15:27
0
Add a comment |
11

You can use the following code with Apache HTTP:

String payload = ""; post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON)); response = client.execute(request); 
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)); 

Источник

POST Request with JSON using Java 11 HttpClient API

Up until now, we have already covered sending a GET Request using Java 11 HttpClient API. If you haven’t checked that, go for it by clicking this link. Now, in this example, we are going to see “How to send a POST request with JSON as request body using Java 11 HttpClient API?” .

Post_HttpClient_Request_Java11_Featured_Image_Techndeck

In this tutorial, we are going to cover below topics:

  1. What is HTTP POST Request?
  2. How to send POST request using HttpClient?

1. What is HTTP POST Request?

POST is one of the most common methods of HTTP which is used to send data to a server to create/update the resource . Data sent to the server is in the form of either Request Body / Request Parameters which is basically used to create or update the resource on the server.

Some key points of POST requests:

  • POST requests parameters doesn’t store in the browser history
  • POST requests are used to send data to the server to create or update the resource
  • POST requests cannot be cached
  • POST requests are secure as compared to GET because parameters/data doesn’t store in browser history
  • POST requests parameter data is unlimited as there are no length restrictions
  • POST requests cannot be bookmarked
  • POST requests allow ASCII characters
  • POST requests are difficult to hack

2. How to send POST request using Java 11 HttpClient?

In this tutorial, we will test the ‘Dummy Sample Rest API’ which is available here. This page contains Fake Online REST API for the testing purposes which are performing various CRUD operations.

Let’s take an example of one of the API POST endpoint available at the above-mentioned website which is ‘/create’. The full-service URL with endpoint is ‘http://dummy.restapiexample.com/api/v1/create‘.

At the above resource URL, we are going to submit data in the form of JSON to create an employee.

JSON Request Body:

Here is the code to send the POST request (containing request body in JSON format) to the above mentioned REST API Service Endpoint:

Let’s try to understand the code:

1. Specify the URL

2. Create a Post Request using HttpRequest builder that takes JSON as input and pass the resource URI to it

3. Create a new HttpClient object

4. Submit the POST Request with BodyHandler which defines the response body should be of string format, and store the output in the response object

5. Finally, extract the status code and response body using the response object created above

Eclipse Console Output:

That’s it, it’s that simple to make a POST Request with JSON body using new Java 11 HttpClient library: ?

If you like this post , please check out my other useful blog posts on Rest Assured:

Other Useful References:

Author

Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks. View all posts

Submit a Comment Cancel reply

Subscribe to our Newsletter

About Techndeck

Techndeck.com is a blog revolves around software development & testing technologies. All published posts are simple to understand and provided with relevant & easy to implement examples.

Techndeck.com’s author is Deepak Verma aka DV who is an Automation Architect by profession, lives in Ontario (Canada) with his beautiful wife (Isha) and adorable dog (Fifi). He is crazy about technologies, fitness and traveling etc. He runs a Travel Youtube Channel as well. He created & maintains Techndeck.com

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Источник

Оцените статью