An article summarizing how to HTTP POST JSON in Java
Only the minimum necessary writing style is summarized.
For the sake of simplicity, we have prepared a JSON format string. Please refer to other articles for how to convert JSON to java.
It is assumed that the caller instantiates this class and calls the execute () method.
The procedure is as follows
Sample.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Sample {
private HttpURLConnection conn;
private URL url;
private String URL ="https://XXX.YY-ZZZZ.com/WWW/";
private String json =
"{" +
" \"searchCondition\": {" +
" \"conditions\": [" +
"{" +
" \"conditionType\": \"Name\","+
" \"Value\": 200," +
" }"+
"]" +
"}," +
"\"outputMethod\": \"split\","+
"\"zipFileName\": \"DDD.zip\"" +
"}";
private String result;
Sample() throws IOException{
//1.Make settings to connect
//Call the openConnection method on the URL to create a connection object
url = new URL(URL);
conn = (HttpURLConnection) url.openConnection();
//Various settings of HttpURLConnection
//Set HTTP method to POST
conn.setRequestMethod("POST");
//Allow body submission of request
conn.setDoInput(true);
//Allow body reception of response
conn.setDoOutput(true);
//Specify Json format
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
// 2.Establish a connection
conn.connect();
}
public String execute() throws IOException{
// 3.Write to request and body
//Get OutputStream from HttpURLConnection and write json string
PrintStream ps = new PrintStream(conn.getOutputStream());
ps.print(json);
ps.close();
// 4.Receive a response
//HttpStatusCode 200 is returned at the end of normal operation
if (conn.getResponseCode() != 200) {
//Error handling
}
//Get InputStream from HttpURLConnection and read
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
// 5.Disconnect
conn.disconnect();
//Return the result to the caller
return result;
}
}
Use the following methods to set HtppURLConnection. For details, please refer to the official reference etc. Use the following method to modify the setup parameters. ・ SetAllowUserInteraction ・ SetDoInput ・ SetDoOutput ・ SetIfModifiedSince ・ SetUseCaches Use the following methods to modify general request properties. ・ SetRequestProperty
Recommended Posts