Here's a summary of how to HTTP POST and HTTP GET JSON in Java. How to do JSON → Java and Java → JSON in Java is summarized in ** Previous article **
- [This article] I will summarize how to POST and GET JSON by HTTP communication in Java </ b> --I will explain two ways to perform HTTP communication with Java. --How to use OkHttp3 --How to use the standard Java package ** HttpUrlConnection **
-[Previous article] Summarize how to handle JSON in Java --There are two ways to convert JSON to Java (serialize) and Java to JSON (serialize). --How to use GSON for the library --How to use Jackson for the library
It is necessary to enable Java → JSON (serialization) and JSON → Java (deserialization) before HTTP communication. The easy way to do that is summarized in ** This article **, so I will skip it here.
JSON that GETs from the server or POSTs to the server considers the code as the following format.
Sample JSON string: example.json
{
"person": {
"firstName": "John",
"lastName": "Doe",
"address": "NewYork",
"pets": [
{"type": "Dog", "name": "Jolly"},
{"type": "Cat", "name": "Grizabella"},
{"type": "Fish", "name": "Nimo"}
]
}
}
In this article, we will focus on HTTP communication.
Explain two approaches
--Method using library (OkHttp3) There are many libraries that can communicate with HTTP, but in this article, we will focus on OkHttp3.
--How to not use the library I will take up the method of using the Java standard package HttpUrlConnection without using an external library.
The library specification method of OkHttp3 is as follows
■ The latest library of OkHttp3 (maven repository) https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp
■ OkHttp3 ** maven ** setting example
pom.xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.1</version>
</dependency>
■ OkHttp3 ** gradle ** setting example
build.gradle
compile 'com.squareup.okhttp3:okhttp:3.14.1'
Below is a sample HTTP client that POSTs a JSON string and receives the resulting string
OkHttpPostClient.java
/**
*Using "OkHttp3" for the HTTP library and "GSON" for the GSON operation library,
*Sample to "POST" JSON to server
*/
public class OkHttpPostClient {
public static void main(String[] args) throws IOException {
OkHttpPostClient client = new OkHttpPostClient();
String result = client.callWebAPI();
System.out.println(result);
}
private static final String WEB_API_ENDPOINT = "http://localhost:8080/api";
public String callWebAPI() throws IOException {
final String postJson = "{" +
" \"person\": {" +
" \"firstName\": \"John\"," +
" \"lastName\": \"Doe\"," +
" \"address\": \"NewYork\"," +
" \"pets\": [" +
" {\"type\": \"Dog\", \"name\": \"Jolly\"}," +
" {\"type\": \"Cat\", \"name\": \"Grizabella\"}," +
" {\"type\": \"Fish\", \"name\": \"Nimo\"}" +
" ]" +
" }" +
"}";
final Map<String, String> httpHeaders = new LinkedHashMap<String, String>();
final String resultStr = doPost(WEB_API_ENDPOINT, "UTF-8", httpHeaders, postJson);
return resultStr;
}
public String doPost(String url, String encoding, Map<String, String> headers, String jsonString) throws IOException {
final okhttp3.MediaType mediaTypeJson = okhttp3.MediaType.parse("application/json; charset=" + encoding);
final RequestBody requestBody = RequestBody.create(mediaTypeJson, jsonString);
final Request request = new Request.Builder()
.url(url)
.headers(Headers.of(headers))
.post(requestBody)
.build();
final OkHttpClient client = new OkHttpClient.Builder()
.build();
final Response response = client.newCall(request).execute();
final String resultStr = response.body().string();
return resultStr;
}
}
The following parts are the points of the code to ** GET **. In the following, specify url and header and execute ** GET **. To get the result as text, use ** response.body (). String () **.
public String doGet(String url, Map<String, String> headers) throws IOException {
final Request request = new Request.Builder()
.url(url)
.headers(Headers.of(headers))
.build();
final OkHttpClient client = new OkHttpClient.Builder().build();
final Response response = client.newCall(request).execute();
final String resultStr = response.body().string();
return resultStr;
}
Below is the full source code. This is an example of accessing http: // localhost: 8080 / api. The server-side code is also posted below for experimentation.
OkHttpGetClient.java(Source code)
public class OkHttpGetClient {
public static void main(String[] args) throws IOException {
OkHttpGetClient client = new OkHttpGetClient();
Model result = client.callWebAPI();
System.out.println("Firstname is " + result.person.firstName);
}
private static final String WEB_API_ENDPOINT = "http://localhost:8080/api";
private final Gson mGson = new Gson();
public Model callWebAPI() throws IOException {
final Map<String, String> httpHeaders = new LinkedHashMap<String, String>();
final String resultStr = doGet(WEB_API_ENDPOINT, httpHeaders);
final Model model = mGson.fromJson(resultStr, Model.class);
return model;
}
public String doGet(String url, Map<String, String> headers) throws IOException {
final Request request = new Request.Builder()
.url(url)
.headers(Headers.of(headers))
.build();
final OkHttpClient client = new OkHttpClient.Builder().build();
final Response response = client.newCall(request).execute();
final String resultStr = response.body().string();
return resultStr;
}
}
Shows the code for a simple Web API server using Jetty as the server side for the experiment
/**
*-When GET, returns a JSON string<br>
*-When JSON is POSTed, it parses JSON and returns the result.<br>
*HTTP server
*/
public class JsonApiServer {
public static void main(String[] args) {
final int PORT = 8080;
final Class<? extends Servlet> servlet = ExampleServlet.class;
ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletHandler.addServlet(new ServletHolder(servlet), "/api");
final Server jettyServer = new Server(PORT);
jettyServer.setHandler(servletHandler);
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("serial")
public static class ExampleServlet extends HttpServlet {
private final Gson mGson = new Gson();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Model model = new Model();
model.person = new Person();
model.person.firstName = "John";
model.person.lastName = "Do";
model.person.address = "New York";
model.person.pets = new ArrayList<Pet>();
Pet pet1 = new Pet();
pet1.type = "dog";
pet1.name = "Jolly";
model.person.pets.add(pet1);
Pet pet2 = new Pet();
pet2.type = "Cat";
pet2.name = "Grizabella";
model.person.pets.add(pet2);
Pet pet3 = new Pet();
pet3.type = "fish";
pet3.name = "Nemo";
model.person.pets.add(pet3);
String json = mGson.toJson(model);
resp.setContentType("text/html; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
final PrintWriter out = resp.getWriter();
out.println(json);
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final StringBuilder sb = new StringBuilder();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
}
final String body = sb.toString();
final Model model = mGson.fromJson(body, Model.class);
resp.setContentType("text/html; charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
final PrintWriter out = resp.getWriter();
out.println("Server Generated Message");
out.println("Firstname is " + model.person.firstName);
out.close();
}
}
}
The source code set is as follows https://github.com/riversun/java-json-gson-jackson-http
HttpUrlConnection is a standard Java package, so you don't need any external libraries **.
Libraries are often convenient and sophisticated, but they are still used when you want to avoid increasing the number of dependent libraries and total methods due to the introduction of multifunctional libraries, such as the wall of DEX file 64K in Android environment. There is room.
As mentioned above, the notation is ** Java 1.6 Compliant ** so that it can be widely used in Java-based environments such as Android.
UrlConnHttpPostClient.java
/**
*Use Java standard "HttpUrlConnection" for HTTP communication and "GSON" for GSON operation library.
*Sample to "POST" JSON from the server
*/
public class UrlConnHttpPostClient {
public static void main(String[] args) throws IOException {
UrlConnHttpPostClientclient = new UrlConnHttpPostClient();
String result = client.callWebAPI();
System.out.println(result);
}
private static final String WEB_API_ENDPOINT = "http://localhost:8080/api";
public String callWebAPI() throws IOException {
final String postJson = "{" +
" \"person\": {" +
" \"firstName\": \"John\"," +
" \"lastName\": \"Doe\"," +
" \"address\": \"NewYork\"," +
" \"pets\": [" +
" {\"type\": \"Dog\", \"name\": \"Jolly\"}," +
" {\"type\": \"Cat\", \"name\": \"Grizabella\"}," +
" {\"type\": \"Fish\", \"name\": \"Nimo\"}" +
" ]" +
" }" +
"}";
final Map<String, String> httpHeaders = new LinkedHashMap<String, String>();
final String resultStr = doPost(WEB_API_ENDPOINT, "UTF-8", httpHeaders, postJson);
return resultStr;
}
private String doPost(String url, String encoding, Map<String, String> headers, String jsonString) throws IOException {
final int TIMEOUT_MILLIS = 0;//Timeout milliseconds: 0 is infinite
final StringBuffer sb = new StringBuffer("");
HttpURLConnection httpConn = null;
BufferedReader br = null;
InputStream is = null;
InputStreamReader isr = null;
try {
URL urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setConnectTimeout(TIMEOUT_MILLIS);//Time to connect
httpConn.setReadTimeout(TIMEOUT_MILLIS);//Time to read data
httpConn.setRequestMethod("POST");//HTTP method
httpConn.setUseCaches(false);//Use cache
httpConn.setDoOutput(true);//Allow sending of request body(False for GET,Set to true for POST)
httpConn.setDoInput(true);//Allow receiving body of response
if (headers != null) {
for (String key : headers.keySet()) {
httpConn.setRequestProperty(key, headers.get(key));//Set HTTP header
}
}
final OutputStream os = httpConn.getOutputStream();
final boolean autoFlash = true;
final PrintStream ps = new PrintStream(os, autoFlash, encoding);
ps.print(jsonString);
ps.close();
final int responseCode = httpConn.getResponseCode();
String _responseEncoding = httpConn.getContentEncoding();
if (_responseEncoding == null) {
_responseEncoding = "UTF-8";
}
if (responseCode == HttpURLConnection.HTTP_OK) {
is = httpConn.getInputStream();
isr = new InputStreamReader(is, _responseEncoding);
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} else {
//Status is HTTP_OK(200)Other than
throw new IOException("responseCode is " + responseCode);
}
} catch (IOException e) {
throw e;
} finally {
// Java1.6 Compliant
if (br != null) {
try {
br.close();
} catch (IOException e) {
}
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (httpConn != null) {
httpConn.disconnect();
}
}
return sb.toString();
}
}
UrlConnHttpGetClient.java
package com.example.http_client.urlconnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import com.example.jackson.Model;
import com.google.gson.Gson;
/**
*Use Java standard "HttpUrlConnection" for HTTP communication and "GSON" for GSON operation library.
*Sample to "GET" JSON from the server
*/
public class UrlConnHttpGetClient {
public static void main(String[] args) throws IOException {
UrlConnHttpGetClient client = new UrlConnHttpGetClient();
Model result = client.callWebAPI();
System.out.println("Firstname is " + result.person.firstName);
}
private static final String WEB_API_ENDPOINT = "http://localhost:8080/api";
private final Gson mGson = new Gson();
public Model callWebAPI() throws IOException {
final Map<String, String> httpHeaders = new LinkedHashMap<String, String>();
final String resultStr = doGet(WEB_API_ENDPOINT, httpHeaders);
final Model model = mGson.fromJson(resultStr, Model.class);
return model;
}
public String doGet(String url, Map<String, String> headers) throws IOException {
final int TIMEOUT_MILLIS = 0;//Timeout milliseconds: 0 is infinite
final StringBuffer sb = new StringBuffer("");
HttpURLConnection httpConn = null;
BufferedReader br = null;
InputStream is = null;
InputStreamReader isr = null;
try {
URL urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setConnectTimeout(TIMEOUT_MILLIS);//Time to connect
httpConn.setReadTimeout(TIMEOUT_MILLIS);//Time to read data
httpConn.setRequestMethod("GET");//HTTP method
httpConn.setUseCaches(false);//Use cache
httpConn.setDoOutput(false);//Allow sending of request body(False for GET,Set to true for POST)
httpConn.setDoInput(true);//Allow receiving body of response
if (headers != null) {
for (String key : headers.keySet()) {
httpConn.setRequestProperty(key, headers.get(key));//Set HTTP header
}
}
final int responseCode = httpConn.getResponseCode();
String encoding = httpConn.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
if (responseCode == HttpURLConnection.HTTP_OK) {
is = httpConn.getInputStream();
isr = new InputStreamReader(is, encoding);
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} else {
//Status is HTTP_OK(200)Other than
throw new IOException("responseCode is " + responseCode);
}
} catch (IOException e) {
throw e;
} finally {
// Java1.6 Compliant
if (br != null) {
try {
br.close();
} catch (IOException e) {
}
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (httpConn != null) {
httpConn.disconnect();
}
}
return sb.toString();
}
}
--I also introduced two ways to do HTTP communication with Java. -** How to use OkHttp3 ** --How to use the standard Java package ** HttpUrlConnection **
--The full source code can be found at here
Recommended Posts