This is the 11th day of my participation in the Novembermore Challenge

There are many ways to send Http requests in Java, record the relevant request methods, this record Jdk built-in HttpURLConnection, simple and concise, simple to use.

1 HttpURLConnection

HttpURLConnection is a built-in request tool of the Jdk. It is applicable to simple scenarios without relying on third-party JAR packages.

To use this method, you get an URLConnection object by calling url. openConnection and forcing it into an HttpURLConnection object.

java.net.URL

    public URLConnection openConnection(a) throws java.io.IOException {
        return handler.openConnection(this);
    }
Copy the code

Java.net.HttpURLConnection part source code:

abstract public class HttpURLConnection extends URLConnection {
    // ...
}
Copy the code

HttpURLConnection is a subclass of URLConnection. Its inner class contains the methods and request codes of its parent class.

Send a GET request, whose main parameters are taken from the URI, as well as request headers,cookies, and other data.

To send a POST request, an HttpURLConnection instance must set setDoOutput(True), whose request body data is written to the output stream returned by HttpURLConnection’s getOutputStream() method.

1 Prepare a SpringBoot project environment

2 Add a controller

@Controller
@Slf4j
public class HelloWorld {

    @Override
    @GetMapping("/world/getData")
    @ResponseBody
    public String getData(@RequestParam Map<String, Object> param) {
        System.out.println(param.toString());
        return 

Hello World getData method

; } @PostMapping("/world/getResult") @ResponseBody public String getResult(@RequestBody Map<String, Object> param) { System.out.println(param.toString()); return

Hello World getResult

; }}Copy the code

Add a utility class that sends requests

package com.cf.demo.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/** * Http request tool class */
@Slf4j
@Data
public class JdkHttpUtils {

    /** * Get the POST request **@returnRequest result */
    public static String getPost(String url, Integer connectTimeout, Integer readTimeout, String contentType, Map
       
         heads, Map
        
          params)
        ,>
       ,> throws IOException {

        URL u;
        HttpURLConnection connection = null;
        OutputStream out;
        try {
            u = new URL(url);
            connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);
            connection.setRequestProperty("Content-Type", contentType);
            // This property must be set for POST requests
            connection.setDoOutput(true);
            connection.setDoInput(true);
            if(heads ! =null) {
                for (Map.Entry<String, String> stringStringEntry : heads.entrySet()) {
                    connection.setRequestProperty(stringStringEntry.getKey(),
                            stringStringEntry.getValue());
                }
            }

            out = connection.getOutputStream();
            if(params ! =null && !params.isEmpty()) {
                out.write(toJSONString(params).getBytes());
            }
            out.flush();
            out.close();

            // Get the data stream returned by the request
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // Encapsulate the input stream is and specify the character set
            int i;
            while((i = is.read()) ! = -1) {
                baos.write(i);
            }
            return baos.toString();

        } catch (Exception e) {
            log.error("Request exception, message = {}", e.getMessage());
        }
        return null;
    }


    /** * Get the POST request **@returnRequest result */
    public static String getGet(String url, Integer connectTimeout, Integer readTimeout, String contentType, Map
       
         heads, Map
        
          params)
        ,>
       ,> throws IOException {

        // Concatenate request parameters
        if(params ! =null && !params.isEmpty()) {
            url += "?";
            if(params ! =null && !params.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (Map.Entry<String, String> stringObjectEntry : params.entrySet()) {
                    try {
                        sb.append(stringObjectEntry.getKey()).append("=").append(
                                URLEncoder.encode(stringObjectEntry.getValue(), "UTF-8"))
                                .append("&");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                sb.delete(sb.length() - 1, sb.length());
                url += sb.toString();
            }
        }

        URL u;
        HttpURLConnection connection;
        u = new URL(url);
        connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setRequestProperty("Content-Type", contentType);
        if(heads ! =null) {
            for(Map.Entry<String, String> stringStringEntry : heads.entrySet()) { connection.setRequestProperty(stringStringEntry.getKey(), stringStringEntry.getValue()); }}// Get the data stream returned by the request
        InputStream is = connection.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Encapsulate the input stream is and specify the character set
        int i;
        while((i = is.read()) ! = -1) {
            baos.write(i);
        }
        return baos.toString();

    }


    /** * Map to Json string */
    public static String toJSONString(Map<String, String> map) {
        Iterator<Entry<String, String>> i = map.entrySet().iterator();
        if(! i.hasNext()) {return "{}";
        }

        StringBuilder sb = new StringBuilder();
        sb.append('{');
        for(; ;) { Map.Entry<String, String> e = i.next(); String key = e.getKey(); String value = e.getValue(); sb.append("\" ");
            sb.append(key);
            sb.append("\" ");
            sb.append(':');
            sb.append("\" ");
            sb.append(value);
            sb.append("\" ");
            if(! i.hasNext()) {return sb.append('} ').toString();
            }
            sb.append(', ').append(' '); }}}Copy the code

4 Add a test tool class

@Slf4j
public class HttpTest {

    // Request an address
    public String url = "";
    // Request header parameters
    public Map<String, String> heads = new HashMap<>();
    // Request parameters
    public Map<String, String> params = new HashMap<>();
    // Data type
    public String contentType = "application/json";
    // Connection timed out
    public Integer connectTimeout = 15000;
    // Read times out
    public Integer readTimeout = 60000;

    @Test
    public void testGET(a) {
        // 1 Add data
        url = "http://localhost:8080/world/getData";
        heads.put("token"."hhhhhhhhhhhaaaaaaaa");
        params.put("username"."libai");

        String result = null;
        try {
            // 2 Send an Http request and obtain the returned result
            result = JdkHttpUtils
                    .getGet(url, connectTimeout, readTimeout, contentType, heads, params);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 3 Print the result
        log.info(result);
    }

    @Test
    public void testPOST(a) {
        // 1 Add data
        url = "http://localhost:8080/world/getResult";
        heads.put("token"."hhhhhhhhhhhaaaaaaaa");
        params.put("username"."libai");

        String result = null;
        try {
            // 2 Send an Http request and obtain the returned result
            result = JdkHttpUtils
                    .getPost(url, connectTimeout, readTimeout, contentType, heads, params);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 3 Print the resultlog.info(result); }}Copy the code

5 Test Results

POST requests test results

/*
[main] INFO com.cf.demo.HttpTest - <h1> Hello World  getResult 方法</h1>

{username=libai}
*/
Copy the code

GET request test results

/* [main] info.cf.demo. HttpTest - 

Hello World getData method

{username=libai} */
Copy the code

References:

www.baeldung.com/java-http-r…