POST Json in Java ~ HttpURLConnection ~

Overview

An article summarizing how to HTTP POST JSON in Java

Only the minimum necessary writing style is summarized.

Premise

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.

procedure

The procedure is as follows

  1. Make settings for connecting with HttpURLConnection
  2. Establish a connection
  3. Write to the request and body
  4. Receive the response
  5. Disconnect

How to communicate with HTTP in Java

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;
	}
}

reference

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

POST Json in Java ~ HttpURLConnection ~
POST JSON in Java
[java] HttpURLConnection POST
Read JSON in Java
Create JSON in Java
Json serialization / deserialization in Java 1.4
Get the result of POST in Java
Partization in Java
How to POST JSON in Java-Method using OkHttp3 and method using HttpUrlConnection-
Changes in Java 11
Rock-paper-scissors in Java
Try using JSON format API in Java
Working with huge JSON in Java Lambda
Pi in Java
FizzBuzz in Java
Code to escape a JSON string in Java
[java] sort in list
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
Comments in Java source
Azure functions in java
Parse Json in Scala
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
Express failure in Java
Date manipulation in Java 8
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
Try using RocksDB in Java
Read binary files in Java 1
Avoid Yubaba's error in Java
[Java] JSON communication with jackson
Get EXIF information in Java
Save Java PDF in Excel
[Neta] Sleep Sort in Java
How to use JSON data in WebSocket communication (Java, JavaScript)
Edit ini in Java: ini4j
Java history in this world
Let Java segfault in 6 lines
Try calling JavaScript in Java
Try developing Spresense in Java (1)