Http Post Using Json in Java

How to send post request in java with a JSON body

This Question is asked before here:
HTTP POST using JSON in Java

See it and comment this if you face any problem.

HTTP POST request with JSON String in JAVA

Finally I managed to find the solution to my problem ...

public static void SaveWorkFlow() throws IOException
{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(myURLgoesHERE);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("task", "savemodel"));
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;
try
{
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
// System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext())
{
System.out.println(in.next());

}
EntityUtils.consume(entity);
} finally
{
in.close();
response.close();
}
}

Can't send JSON in a Java HTTP POST request

Thanks to Andreas, it was just missing the line :

connection.setRequestProperty("Content-Type", "application/json");

It works fine now.

Sending JSON Post HTTP request in java

Updating the apache HttpCore version to 4.4.3 worked for me

How to perform a post request using json file as body

I recommend you to parse JSON file to String from this topic:
How to read json file into java with simple JSON library

Then you can take your JSON-String and parse to Map (or whatever you specify) by popular and simple library Gson.

String myJSON = parseFileToString();  //get your parsed json as string
Type mapType = new TypeToken<Map<String, String>>(){}.getType(); //specify type of
your JSON format
Map<String, String> = new Gson().fromJson(myJSON, mapType); //convert it to map

Then you can pass this map as a request body to your post. Dont pass any JSON data as URL in POST methods.
Data in URL isn't good idea as long as you are not using GET (for example).

You can also send whole JSON (in String version) as parameter, without converting it to Maps or objects. This is only example :)

And if you want to pass this map in your POST method you can follow this topic:
Send data in Request body using HttpURLConnection

[UPDATE] it worked fine, result 200 OK from server, no exceptions, no errors:

   package com.company;

import java.io.DataInputStream;
import java.io.File;
//import org.json.JSONObject;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class TestAuth {

public static void main(String[] args) {
// TODO Auto-generated method stub

File file = new File("test.json");
try {
JSONParser parser = new JSONParser();
//Use JSONObject for simple JSON and JSONArray for array of JSON.
JSONObject data = (JSONObject) parser.parse(
new FileReader(file.getAbsolutePath()));//path to the JSON file.
System.out.println(data.toJSONString());

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");

URL url2 = new URL("https://0c193bc3-8439-46a2-a64b-4ce39f60b382.mock.pstmn.io");
HttpsURLConnection conn = (HttpsURLConnection) url2.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "Bearer aanjd-usnss092-mnshss-928nss");

conn.setDoOutput(true);
OutputStream outStream = conn.getOutputStream();
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
outStreamWriter.write(data.toJSONString());
outStreamWriter.flush();
outStreamWriter.close();
outStream.close();
String response = null;

System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());

DataInputStream input = null;
input = new DataInputStream (conn.getInputStream());
while (null != ((response = input.readLine()))) {
System.out.println(response);
input.close ();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}

Let me know if that answer fixed your problem. Greetings!

HTTP POST from Java with JSON issue

so there are a few caveats with this. I got this working after making a few changes.

  1. Make sure to set the charset.
setRequestProperty("charset", "utf-8");

  1. Dont wrap the OutputStream, put it in a try-with-resources, and write the json as a byte array as utf-8 since that what we're accepting.
try (OutputStream output = httpcon.getOutputStream()) {
output.write(json.toString().getBytes(StandardCharsets.UTF_8));
}

  1. Make sure your Json object is correct. If you're going to use accountID make sure you're consuming it properly. Gson/Jackson for example won't be able to parse this as conventionally it would accept account_id or accountId. Use @JsonProperty if needed.
@JsonProperty("account_id")
private final String accountId;

Example Controller with Spring Boot

@RestController
public class TestPostController {

public static class Account {

@JsonProperty("account_id")
private final String accountId;

public Account(String accountId) {
this.accountId = accountId;
}

public Account() {
this(null);
}

public String getAccountId() {
return accountId;
}
}
@PostMapping(path = "/test-post", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Account> response(@RequestBody Account account) {
return ResponseEntity.ok(account);
}

}


Related Topics



Leave a reply



Submit