Java request Http interface-hutool's HttpUtil (super detailed-with tool class)

Overview

HttpUtil is a tool class encapsulation that handles Http requests in simple scenarios. This tool encapsulates common operations of the HttpRequest object and can ensure that the Http request is completed within one method.

This module is encapsulated based on JDK's HttpUrlConnection and fully supports https, proxy and file upload.

Guide package

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.1</version>
        </dependency>

Read the page and return the entire page content message

For the most commonly used GET and POST requests, HttpUtil encapsulates two methods:

  • HttpUtil.get

  • The two HttpUtil.post methods are used to request ordinary pages, and then return the string of the page content. They also provide some overloaded methods for specifying request parameters (the specified parameters support File objects, which can realize file upload, of course only for POST requests ) .

get request page

	// 最简单的HTTP请求,可以自动通过header等信息判断编码,不区分HTTP和HTTPS
String result1= HttpUtil.get("https://www.baidu.com");

// 当无法识别页面编码的时候,可以自定义请求页面的编码
String result2= HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8);

//可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");

String result3= HttpUtil.get("https://www.baidu.com", paramMap);

Return results:
Insert image description here

post request page

HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");

String result= HttpUtil.post("https://www.baidu.com", paramMap);

upload files

HashMap<String, Object> paramMap = new HashMap<>();
//文件上传只需将参数中的键指定(默认file),值设为文件对象即可,对于使用者来说,文件上传与普通表单提交并无区别
paramMap.put("file", FileUtil.file("D:\\face.jpg"));

String result= HttpUtil.post("https://www.baidu.com", paramMap);

download file

Because of the Hutool-http mechanism problem, the return result of the request page is parsed into byte[] at once. If the return result of the request URL is too large (such as file download), the memory will explode, so HttpUtil is separately encapsulated for file download. When file downloads are faced with large files, they are read and written in a streaming manner. Only a certain amount of cache is retained in the memory, and then written to the hard disk in blocks, so there is no pressure on the memory in the case of large files.

String fileUrl = "http://mirrors.sohu.com/centos/8.4.2105/isos/x86_64/CentOS-8.4.2105-x86_64-dvd1.iso";

//将文件下载后保存在E盘,返回结果为下载文件大小
long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"));
System.out.println("Download size: " + size);

Of course, if we want to sense the download progress, we can also use another overloaded method to call back to sense the download progress:

//带进度显示的文件下载
HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"), new StreamProgress(){
    
    
    
    @Override
    public void start() {
    
    
        Console.log("开始下载。。。。");
    }
    
    @Override
    public void progress(long progressSize) {
    
    
        Console.log("已下载:{}", FileUtil.readableFileSize(progressSize));
    }
    
    @Override
    public void finish() {
    
    
        Console.log("下载完成!");
    }
});

Other methods

  • HttpUtil.encodeParams encodes URL parameters, only encoding keys and values. The provided values ​​can be parameters attached to the url, but not just the url.
  • HttpUtil.toParams and HttpUtil.decodeParams are two methods that convert Map parameters into URL parameter strings and convert URL parameter strings into Map objects.
  • HttpUtil.urlWithForm is used to concatenate the URL string and Map parameters into a complete string for GET requests.
  • HttpUtil.getMimeType quickly obtains the MimeType based on the file extension (the parameter can also be the complete file path)

result interface

Essentially, the get and post tool methods in HttpUtil are encapsulations of the HttpRequest object, so if you want to operate Http requests more flexibly, you can use HttpRequest.

get request

public static JSONObject get(String url, Map<String, Object> queryParams, Map<String, String> headers) throws IOException {
    
    
        String body = HttpRequest.get(url).form(queryParams).addHeaders(headers).execute().body();
        return JSONObject.parseObject(body);
    }

post form request

 public static JSONObject post(String url, Map<String, Object> queryParams, Map<String, String> headers) {
    
    
        String body = HttpRequest.post(url)
                .header(Header.USER_AGENT, "Hutool http")//头信息,多个头信息多次调用此方法即可
                .form(queryParams)//表单内容
                .timeout(20000)//超时,毫秒
                .execute().body();
        return JSONObject.parseObject(body);
    }

post -json request

 public static JSONObject post(String url, String json, Map<String, String> headers) {
    
    
        String body = HttpRequest.post(url).body(json).addHeaders(headers).execute().body();
        return JSONObject.parseObject(body);
    }

Configure proxy

String result2 = HttpRequest.post(url)
    .setHttpProxy("127.0.0.1", 9080)
    .body(json)
    .execute().body();

Guess you like

Origin blog.csdn.net/qq_41694906/article/details/132355739