HttpClient系列(一),JDK HttpURLConnection

目录



正文


2020年5月23日,星期六,阴雨绵绵。

天气不怎么好,在家闲着,倒不如更新下博客。将经常用到的HttpClient创建方法做成一个系列。以JDK自带的HttpURLConnection作为一个开端,后面会陆续包含Apache HttpClient、Spring RestTemplate、OkHttp、Vert.x HttpClient、Netty HttpClient,各写一个GET与POST请求的Demo。

笔者一贯秉承着能动手的时候就不说话,所以就直接开干了,创建一个JdkHttpUtil类,先写GET请求。

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.nio.charset.StandardCharsets;

public class JdkHttpUtil {
    private JdkHttpUtil() {}

    public static String get(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        InputStream is = urlConnection.getInputStream();
        BufferedReader reader =new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        StringBuilder content = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
        reader.close();
        is.close();
        return content.toString();
    }
}

接下来再写一个POST请求

public static String post(String urlStr, byte[] payload) throws IOException {
    URL url = new URL(urlStr);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("POST");

    urlConnection.setDoOutput(true); // 设置参数输入,在POST请求这个必须设置为true
    OutputStream os = urlConnection.getOutputStream();
    os.write(payload); // 写入数据
    os.flush(); // 刷新,这一步一定不要忘记了
    os.close();

    InputStream is = urlConnection.getInputStream();
    BufferedReader reader =new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
    StringBuilder content = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        content.append(line);
    }
    reader.close();
    is.close();
    return content.toString();
}

从这上面的代码可以看到,POST请求比GET请求只多了5行代码,具体功能在代码后面的注释有说明。

测试代码

public static void main( String[] args ) throws IOException {
    String content = JdkHttpUtil.get("http://www.baidu.com");
    System.out.println(content);

    String fromData = "page=1&count=5";
    content = JdkHttpUtil.post("https://api.apiopen.top/getWangYiNews", fromData.getBytes());
    System.out.println(content);
}

测试结果

源代码地址:https://gitee.com/dev-tang/httpclient-demo.git

本博客采用 知识共享署名-禁止演绎 4.0 国际许可协议 进行许可

本文标题:HttpClient系列(一),JDK HttpURLConnection

本文地址:https://jizhong.plus/post/2020/05/httpclient-jdk.html