本文采用hutool相关的封装好的http请求,以下是相关请求 测试
介绍
本质上,HttpUtil中的get和post工具方法都是HttpRequest对象的封装,因此如果想更加灵活操作Http请求,可以使用HttpRequest。
使用
// 普通表单 POST请求为例
@Test
public void test() {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("grant_type", "xx");
paramMap.put("client_id", "xx");
paramMap.put("client_secret", "xx");
//链式构建请求
String result2 = HttpRequest.post("http://localhost:10009/oauth/token")
.header(Header.USER_AGENT, "Hutool http") // 头信息,多个头信息多次调用此方法即可
.form(paramMap)//表单内容
.timeout(20000)//超时,毫秒
.execute().body();
Console.log(result2);
}
// Restful请求
@Test
public void test2() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("url", "xxxx");
jsonObject.put("prob", "xxxx");
jsonObject.put("rotate","xxxx" );
jsonObject.put("table", "xxxx");
jsonObject.put("sortPage", "xxxx");
jsonObject.put("charInfo", "xxxx");
//链式构建请求
String result2 = HttpRequest.post("https://ocrapi-advanced.taobao.com/ocrservice/advanced")
.header(Header.AUTHORIZATION, "APPCODE xxxxxxxxxxxxxxxxxxxxxxxx")//头信息,多个头信息多次调用此方法即可
.body(jsonObject.toJSONString())
.timeout(20000)//超时,毫秒
.execute().body();
Console.log(result2);
}
// get请求
@Test
public void test3() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("courtNo", "xx");
jsonObject.put("caseNo", "xx");
//链式构建请求
String result2 = HttpRequest.get("http://localhost:10009/xxx/xx")
.header(Header.AUTHORIZATION, "bearer 0fc41dee-83b4-46f8-aeb8-ce64f7549ef4")//头信息,多个头信息多次调用此方法即可
.body(jsonObject.toJSONString())
.timeout(20000)//超时,毫秒
.execute().body();
Console.log(result2);
}
通过链式构建请求,我们可以很方便的指定Http头信息和表单信息,最后调用execute方法即可执行请求,返回HttpResponse对象。HttpResponse包含了服务器响应的一些信息,包括响应的内容和响应的头信息。通过调用body方法即可获取响应内容。
配置代理
String result2 = HttpRequest.post(url)
.setHttpProxy("127.0.0.1", 9080)
.body(json)
.execute().body();
如果需要自定其他类型代理或更多的项目,可以:
String result2 = HttpRequest.post(url)
.setProxy(new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(host, port))
.body(json)
.execute().body();
其它自定义项
同样,我们通过HttpRequest可以很方便的做以下操作:
- 指定请求头
- 自定义Cookie(cookie方法)
- 指定是否keepAlive(keepAlive方法)
- 指定表单内容(form方法)
- 指定请求内容,比如rest请求指定JSON请求体(body方法)
- 超时设置(timeout方法)
- 指定代理(setProxy方法)
- 指定SSL协议(setSSLProtocol)
- 简单验证(basicAuth方法)