apache-httpclient使用方法(入门)

转载请注明出处https://blog.csdn.net/qq_28630527/article/details/119111791

1.目录

目录

1.目录

2.项目依赖

1.jdk及springboot版本

2.配置文件

3.基础类

1.响应接收类BaseResponse

2.响应状态码常量类ResultCode

3.教师类Teacher(用于当做post请求的requestBody)

3.构建HttpClient对象

1.构建HttpClient对象,发送第一个http请求

2.将HttpClient对象交给Spring容器管理

4.发送get请求

1.处理器类提供HttpGetController

2.使用url无参get请求

3.使用url拼接参数get请求

4.构建URI对象,增加键值对参数get请求

5.发送post请求

1.处理器类提供HttpPostController

2.无参post请求

3.有参post请求,参数包含requestBody和pathParam(使用URI构建)


注:为方便阅读以及代码整洁,本文引入lombok,@Slf4j注解方便日志打印,Header的添加在发送post请求的演示中体现.

2.项目依赖

1.jdk及springboot版本

jdk8 

spring-boot-starter-parent 2.5.2

2.配置文件

application.properties

server.port=80
spring.application.name=apache-httpclient-demo

pom.xml dependency


	com.alibaba
	fastjson
	1.2.76


	org.apache.httpcomponents
	httpclient
	4.5.13

3.基础类

1.响应接收类BaseResponse

/**
 * 基础响应封装类
 *
 * @param 
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BaseResult implements Serializable {
    private String code;
    private String message;
    private T data;

    public BaseResult(ResultCode resultCode, T data) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMessage();
        this.data = data;
    }

    private static final BaseResult DEFAULT_SUCCESS_RESULT = new BaseResult<>(ResultCode.SUCCESS, null);

    public static  BaseResult create(String code, String msg, T data) {
        return new BaseResult<>(code, msg, data);
    }

    public static  BaseResult create(ResultCode resultCode, T data) {
        return new BaseResult<>(resultCode.getCode(), resultCode.getMessage(), data);
    }

    public static  BaseResult success(T data) {
        return create(ResultCode.SUCCESS, data);
    }

    public static  BaseResult success() {
        return success(null);
    }

    public static  BaseResult fail(String code, String msg, T data) {
        return create(code, msg, data);
    }

    public static  BaseResult fail(ResultCode resultCode, T data) {
        return create(resultCode, data);
    }

    public static  BaseResult fail(String code, String msg) {
        return create(code, msg, null);
    }

    public static  BaseResult fail(ResultCode resultCode) {
        return create(resultCode, null);
    }
} 
  

2.响应状态码常量类ResultCode

/**
 * 响应状态码及描述基础类
 */
@Getter
@AllArgsConstructor
public enum ResultCode {
    SUCCESS("200", "成功"),
    ERROR("500", "系统异常"),
    ;
    final String code;
    final String message;
}

3.教师类Teacher(用于当做post请求的requestBody)

/**
 * 老师类,用于测试post请求
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher implements Serializable {
    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 住址
     */
    private String addr;

    /**
     * 学生姓名集合
     */
    private List students;

    /**
     * 课程表{key:星期几,value:课程名称}
     */
    private Map projectTable;
}

3.构建HttpClient对象

注:这里演示了一个简单的HttpClient对象的构建过程,之后的get和post请求演示将由spring容器管理HttpClient对象,使用时注入即可.

1.构建HttpClient对象,发送第一个http请求

/**
 * httpclient构建演示
 */
@Test
@SneakyThrows
void httpClientBuildTest() {

	//构建RequestConfig,并设置连接超时时间
	RequestConfig requestConfig = RequestConfig.custom()
			.setConnectTimeout(5_000)				//连接超时时间5s
			.setConnectionRequestTimeout(5_000)		//请求连接时间5s
			.setSocketTimeout(5_000).build();		//读写时间5s

	//构建HttpClient对象,设置默认RequestConfig,并发送get请求
	HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
	HttpResponse response = httpClient.execute(new HttpGet("http://localhost:80/testController/test"));

	//遍历打印所有响应头内容
	Arrays.stream(response.getAllHeaders()).forEach(header -> {
		log.info("header_key:{},header_value:{}", header.getName(), header.getValue());
		//header_key:Content-Type,header_value:application/json
		//header_key:Transfer-Encoding,header_value:chunked
		//header_key:Date,header_value:Mon, 26 Jul 2021 06:19:45 GMT
		//header_key:Keep-Alive,header_value:timeout=60
		//header_key:Connection,header_value:keep-alive
	});

	//获取响应体内容
	HttpEntity entity = response.getEntity();
	log.info("响应体内容:{}", EntityUtils.toString(entity));//响应体内容:{"code":"200","message":"成功","data":null}

}

2.将HttpClient对象交给Spring容器管理

/**
 * 在spring容器中注入HttpClient默认对象
 */
@Component
public class SpringBeanConfig {

    /**
     * Default-RequestConfig对象,用于设置相关超时时间
     *
     * @return
     */
    @Bean
    public RequestConfig getRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(5_000)               //连接超时时间5s
                .setConnectionRequestTimeout(5_000)     //请求连接时间5s
                .setSocketTimeout(5_000).build();       //读写时间5s
    }

    /**
     * Default-HttpClient对象
     *
     * @param cfg
     * @return
     */
    @Bean
    public HttpClient httpClient(@Autowired RequestConfig cfg) {
        return HttpClientBuilder.create().setDefaultRequestConfig(cfg).build();
    }

}

4.发送get请求

1.处理器类提供HttpGetController

/**
 * 用于处理get请求的Controller
 */
@RestController
@RequestMapping("/httpGetController")
public class HttpGetController {

    /**
     * 无参get请求
     *
     * @return
     */
    @GetMapping("/get")
    public BaseResult get() {
        return BaseResult.success();
    }

    /**
     * 有参get请求
     *
     * @param name
     * @param age
     * @return
     */
    @GetMapping("/getWithParams")
    public BaseResult getWithParams(String name, Integer age) {
        HashMap resultMap = new HashMap<>();
        resultMap.put("name", name);
        resultMap.put("age", age);
        return BaseResult.success(resultMap);
    }
} 
  

2.使用url无参get请求

@Autowired
private HttpClient httpClient;

/**
 * 无参get请求
 */
@Test
@SneakyThrows
void get() {
	HttpResponse response = httpClient.execute(new HttpGet("http://localhost/httpGetController/get"));
	log.info(EntityUtils.toString(response.getEntity()));//{"code":"200","message":"成功","data":null}
}

3.使用url拼接参数get请求

/**
 * 有参get请求,参数直接使用url+params字符串拼接
 */
@Test
@SneakyThrows
void getWithParams() {
	String url = "http://localhost/httpGetController/getWithParams";
	//url中如果存在中文字符,建议先进行转义,否则可能出现'?'或乱码,java.net.URLEncoder
	String params = "?name=" + URLEncoder.encode("张三", "UTF-8") + "&age=" + 23;
	HttpResponse response = httpClient.execute(new HttpGet(url + params));
	log.info(EntityUtils.toString(response.getEntity()));//{"code":"200","message":"成功","data":{"name":"张三","age":23}}
}

4.构建URI对象,增加键值对参数get请求

/**
 * 有参get请求,参数使用java.net.URI工具类拼接
 */
@Test
@SneakyThrows
void getWithParamsURI() {
	List pairList = Arrays.asList(new BasicNameValuePair("name", "李四"), new BasicNameValuePair("age", "24"));
	URI uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(80).setPath("/httpGetController/getWithParams").setParameters(pairList).build();
	HttpResponse response = httpClient.execute(new HttpGet(uri));
	log.info(EntityUtils.toString(response.getEntity()));//{"code":"200","message":"成功","data":{"name":"李四","age":24}}
}

5.发送post请求

1.处理器类提供HttpPostController

/**
 * 用于处理post请求的Controller
 */
@RestController
@RequestMapping("/httpPostController")
public class HttpPostController {

    /**
     * 无参post请求
     *
     * @return
     */
    @PostMapping("/post")
    public BaseResult post() {
        return BaseResult.success("这是无参post请求");
    }


    /**
     * post请求,参数为PathParam和requestBody
     *
     * @param teacher
     * @param name
     * @param age
     * @return
     */
    @PostMapping("/postWithRequestBodyURI")
    public BaseResult postWithRequestBodyURI(
            @RequestBody Teacher teacher
            , /*@RequestParam("name") */String name
            , /*@RequestParam("age") */Integer age) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("param_name", name);
        jsonObject.put("param_age", age);
        jsonObject.put("body", teacher);
        return BaseResult.success(jsonObject.toJSONString());
    }
} 
  

2.无参post请求

/**
 * 无参post请求
 */
@Test
@SneakyThrows
void postNoParam() {
	HttpResponse response = httpClient.execute(new HttpPost("http://localhost/httpPostController/post"));
	log.info(EntityUtils.toString(response.getEntity()));//{"code":"200","message":"成功","data":"这是无参post请求"}
}

3.有参post请求,参数包含requestBody和pathParam(使用URI构建)

/**
 * 使用java.net.URI构建请求url
 * 增加requestBody内容
 */
@Test
@SneakyThrows
void postWithRequestBodyURI() {

	//请求路径
	URI uri = new URIBuilder()
			.setScheme("http")
			.setHost("localhost")
			.setPort(80)
			.setPath("/httpPostController/postWithRequestBodyURI")
			.setParameters(Lists.list(new BasicNameValuePair("name", "赵六"), new BasicNameValuePair("age", "26")))
			.build();

	//requestBody
	HashMap projectTable = new HashMap<>();
	projectTable.put("Mon", "语文");
	projectTable.put("Tus", "数学");
	projectTable.put("Wed", "英语");

	Teacher teacher = new Teacher("赵六", 26, "北京昌平", Lists.list("张三", "李四", "王五"), projectTable);//org.assertj.core.util.Lists
	String requestDetail = JSONObject.toJSONString(teacher);

	//设置请求头,请求体
	HttpPost httpPost = new HttpPost(uri);
	httpPost.setHeader("Content-Type", "application/json;charset=utf8");
	httpPost.setEntity(new StringEntity(requestDetail, "UTF-8"));

	//发送post请求
	HttpResponse response = httpClient.execute(httpPost);
	String responseStr = EntityUtils.toString(response.getEntity());
	log.info("response is:{}", responseStr);//response is:{"code":"200","message":"成功","data":"{\"param_age\":26,\"body\":{\"addr\":\"北京昌平\",\"age\":26,\"name\":\"赵六\",\"projectTable\":{\"Tus\":\"数学\",\"Wed\":\"英语\",\"Mon\":\"语文\"},\"students\":[\"张三\",\"李四\",\"王五\"]},\"param_name\":\"赵六\"}"}
	JSONObject respObj = JSONObject.parseObject(responseStr);
	JSONObject data = JSONObject.parseObject(respObj.getString("data"));
	log.info("data is:{}", data);//data is:{"param_age":26,"body":{"name":"赵六","projectTable":{"Tus":"数学","Wed":"英语","Mon":"语文"},"students":["张三","李四","王五"],"addr":"北京昌平","age":26},"param_name":"赵六"}

}

演示代码已提交至码云

        https://gitee.com/bjbg/apache-httpclient-demo.git

参考文章

        HttpClient详细使用示例_JustryDeng-CSDN博客_httpclient

你可能感兴趣的:(学习笔记,java)