JDK 自带的HTTP工具类:

java.net.HttpURLConnection

简单的HTTP请求可以用其来实现:

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 简单 http 接口请求工具类
 * </p>
 *
 * @author snail
 * @since 2021/3/12
 */
@Slf4j
public class SimpleHTTPRestUtil {

    public static String doGet(String link) throws IOException {
        URL url = new URL(link);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        try (InputStream inputStream = urlConnection.getInputStream();
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {

            String line;
            StringBuffer sb = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

            return sb.toString();

        } finally {
            urlConnection.disconnect();
        }
    }

    public static String doPostTypeJson(String link, String json) throws IOException {

        URL url = new URL(link);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);// POST方式不能缓存数据
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

        try (OutputStream os = urlConnection.getOutputStream();
             DataOutputStream dos = new DataOutputStream(os)) {

            dos.write(json.getBytes(StandardCharsets.UTF_8));

            try (InputStream inputStream = urlConnection.getInputStream();
                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {

                String line = null;
                StringBuffer sb = new StringBuffer();
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }

                return sb.toString();

            }


        } finally {
            urlConnection.disconnect();
        }
    }

}

缺点是不支持HTTP/2以及WebSocket,从JDK9开始,增加了新的HttpClient,用来代替旧的HttpUrlConnection API,用法也非常简单。

创建请求

HttpClient client = HttpClient.newBuilder()
	.version(Version.HTTP_1_1)
	.followRedirects(Redirect.NORMAL)
	.connectTimeout(Duration.ofSeconds(20))
	.proxy(ProxySelector.of(...))
	.authenticator(Authenticator.getDefault())
	.build();

支持同步或异步请求

HttpResponse<String> response =
      client.send(request, 
      	BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());

client.sendAsync(request, 
	BodyHandlers.ofString())
      .thenApply(response -> 
      	{ System.out.println
      		(response.statusCode());
               return response; 
       } )
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println);

也支持rective stream方式,此种方式 HttpRequest 相当于一个发布者,HttpResponse 相当于消费者

public abstract class HttpRequest {
    ...
    public interface BodyPublisher
        extends Flow.Publisher<ByteBuffer> 
        	{ ... }
}

public abstract class HttpResponse<T> {
    ...
    public interface BodyHandler<T> {
        BodySubscriber<T> 
        	apply(int statusCode, 
        	HttpHeaders responseHeaders);
    }

    public interface BodySubscriber<T>
        extends 
        	Flow.Subscriber<List<ByteBuffer>> 
        { ... }
}


参考:The new HTTP Client API - Sip of Java