httpclient利用hutool工具发送请求

糊涂工具包


<dependency>
    <groupId>cn.hutoolgroupId>
    <artifactId>hutool-allartifactId>
    <version>5.8.20version>
dependency>

发送请求

package cn.fox.mydemo;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Demo1 {
    public void sendRequest(){

        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("key", "value");

        String url = "";
        HttpRequest httpRequest = new HttpRequest(url)
                .header(Header.CONTENT_TYPE, "application/json; charset=UTF-8")
                .header(Header.ACCEPT, "application/json")
//                .header(Header.CONTENT_TYPE, "multipart/form-data; boundary=")
//                .header(Header.ACCEPT, "*/*")
                .header(Header.ACCEPT_ENCODING, "");


//        get请求参数在url上面
//        httpRequest.method(Method.GET);

        httpRequest.method(Method.POST);
        httpRequest.body(JSONObject.toJSONString(requestMap));

        // 执行请求
        HttpResponse response = httpRequest.execute();
        Map map = new HashMap<String, Object>();
        try {
            String body = response.body();
            map = new ObjectMapper().readValue(body, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(map);
    }
}

你可能感兴趣的:(Java,java)