How to POST JSON in Java-Method using OkHttp3 and method using HttpUrlConnection-

Overview

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

Preparation

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.

How to communicate with HTTP in Java

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.

POST and GET JSON using OkHttp3

OkHttp3 library dependencies

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'

HTTP POST JSON using OkHttp3

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

HTTP GET JSON using OkHttp3

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

}

Server-side source code

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

POST and GET JSON using HttpUrlConnection

Dependent libraries

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.

HTTP POST JSON using HttpUrlConnection

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

HTTP GET JSON using HttpUrlConnection

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

Summary

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

How to POST JSON in Java-Method using OkHttp3 and method using HttpUrlConnection-
How to convert A to a and a to A using AND and OR in Java
POST Json in Java ~ HttpURLConnection ~
[Android] Convert Map to JSON using GSON in Kotlin and Java
How to have params in link_to method
How to assemble JSON directly in Jackson
How to test a private method in Java and partially mock that method
How to change the maximum and maximum number of POST data in Spark
How to output Excel and PDF using Excella
How to execute and mock methods using JUnit
[Ruby] How to use gsub method and sub method
How to play audio and music using javascript
[Ruby] How to calculate the total amount using the initialize method and class variables
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
How to add characters to display when using link_to method
Understand how to use Swift's JSON Decoder in 3 minutes
How to mock a super method call in PowerMock
POST JSON in Java
How to handle TSV files and CSV files in Ruby
How to create and execute method, Proc, Method class objects
How to implement a circular profile image in Rails using CarrierWave and R Magick
How to launch Swagger UI and Swagger Editor in Docker
How to get the class name / method name running in Java
How to use the getter / setter method (in object orientation)
How to test including images when using ActiveStorage and Faker
How to specify character code and line feed code in JAXB
How to use JSON data in WebSocket communication (Java, JavaScript)
How to separate words in names in classes, methods, and variables
[Forge] How to register your own Entity and Entity Render in 1.13.2
[Rails] How to define macros in Rspec and standardize processing
How to set character code and line feed code in Eclipse
What happened in "Java 8 to Java 11" and how to build an environment
How to set and describe environment variables using Rails zsh
How to call and use API in Java (Spring Boot)
How to deploy jQuery in your Rails app using Webpacker
Create API to send and receive Json data in Spring
How to develop and register a Sota app in Java
Differences in how to handle strings between Java and Perl
How to join a table without using DBFlute and sql
How to monitor application information in real time using JConsole
How to install PHP 7.4 and SQL Server drivers in CentOS 7.7
[Xcode] How to arrange Xcode and Simulator screens in full screen
How to include PKCE Code_Verifier and Code_Challenge in JMeter requests
How to dynamically switch between FIN and RST in Netty
How to control transactions in Spring Boot without using @Transactional
[rails] How to post images
How to create a method
How to authorize using graphql-ruby
Method definition location Summary of how to check When defined in the project and Rails / Gem
How to deal with 405 Method Not Allowed error in Tomcat + JSP
[Webpacker] Summary of how to install Bootstrap and jQuery in Rails 6.0
Unable to get resources when using modules in Gradle and IntelliJ
How to set and use profile in annotation-based Configuration in Spring framework
[jOOQ] How to CASE WHEN in the WHERE / AND / OR clause
[Rails] How to upload images to AWS S3 using Carrierwave and fog-aws
How to delete large amounts of data in Rails and concerns
How to install the language used in Ubuntu and how to build the environment
How to store the information entered in textarea in a variable in the method
How to get and add data from Firebase Firestore in Ruby
[Rails] How to upload images to AWS S3 using refile and refile-s3
How to solve the unknown error when using slf4j in Java