<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.6</version>
</dependency>
使用案例
1.httpUtil使用post和get请求
String url = "https://xxx/xx";//指定URL
Map<String, Object> map = new HashMap<>();//存放参数
map.put("a", 1);
HashMap<String, String> headers = new HashMap<>();//存放请求头,可以存放多个请求头
headers.put("xxx", xxx);
//发送get请求并接收响应数据
String result= HttpUtil.createGet(url).addHeaders(headers).form(map).execute().body();
//发送post请求并接收响应数据
String result= HttpUtil.createPost(url).addHeaders(headers).form(map).execute().body();
2.向指定URL发送DELETE请求,并携带请求头headers。
String url = "https://xxx/delete/"+id;//指定URL携带ID
HashMap<String, String> headers = new HashMap<>();//存放请求头,可以存放多个请求头
headers.put("xxx", xxx);
//发送delete请求并接收响应数据
String result= HttpUtil.createRequest(Method.DELETE, url).addHeaders(headers).execute().body();
3.Http请求-HttpRequest
本质上,HttpUtil中的get和post工具方法都是HttpRequest对象的封装,因此如果想更加灵活操作Http请求,可以使用HttpRequest。
@Test
public void testHttps() throws Exception {
JSONObject json = new JSONObject();
json.put("username", "1332788xxxxxx");
json.put("password", "123456.");
String result = HttpRequest.post("https://api2.bmob.cn/1/users")
.header("Content-Type", "application/json")//头信息,多个头信息多次调用此方法即可
.header("X-Bmob-Application-Id","2f0419a31f9casdfdsf431f6cd297fdd3e28fds4af")
.header("X-Bmob-REST-API-Key","1e03efdas82178723afdsafsda4be0f305def6708cc6")
.body(json)
.execute().body();
System.out.println(result);
}