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 ~
Create JSON in Java
Json serialization / deserialization in Java 1.4
Working with huge JSON in Java Lambda
Pi in Java
FizzBuzz in Java
Boyer-Moore implementation 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
First Java development in Eclipse
Implement functional quicksort in Java
List aggregation in Java (Collectors.groupingBy)
Reproduce Java enum in C #
Importing Excel data in Java 3
External process execution in Java
About abstract classes in java
Implement rm -rf in Java.
Implementation of tri-tree in Java
Exception handling techniques in Java
Deep copy collection in Java
I tried metaprogramming in Java
View current date in Java
[Java] Basic terms in programming
Implement XML signature in Java
[Android] Convert Map to JSON using GSON in Kotlin and Java
Multithreaded to fit in [Java] template
Various threads in java
I made an annotation in Java.
Express Java try-catch-finally in Scala's scala.util.Try
HTTPS connection using tls1.2 in Java 6
I tried using JWT in Java
How to use classes in Java?
How to name variables in Java
Try running AWS X-Ray in Java
About file copy processing in Java
Try to implement Yubaba in Java
Age guessing game made in Java
Creating lexical analysis in Java 8 (Part 2)
Solve AtCoder Beginner Contest 152 in java
Get stuck in a Java primer
Settings for SSL debugging in Java
Java + OpenCV 3.X in IntelliJ IDEA
Solve AtCoder Beginner Contest 156 in java
1 Implement simple lexical analysis in Java
List of types added in Java 9
Play with Markdown in Java flexmark-java
Catch multiple exceptions together in java
Java draws shapes in PDF documents
Java HashMap Transform js json Formal
Sample vending machine made in Java
How arrays work in Java (illustration)
JPA (Java Persistence API) in Eclipse
Implementation of like function in Java
Do you use Stream in Java?
Creating lexical analysis in Java 8 (Part 1)
Hello world in Java and Gradle
Run an external process in Java
How to concatenate strings in java