Java中有很多封装http请求的util包,我本人觉得最好用的是htool下面的HttpUtil和HttpRequest。代码很简洁,满足我对http操作的所有需求,嘎嘎好用,推荐给大家!
一、第一个HttpUtil,这个可以用于简单的Get和Post请求
1、GET请求例子:
// 最简单的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);
2、POST请求例子:
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");
String result= HttpUtil.post("https://www.baidu.com", paramMap);
3、下载文件:
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);
二、第二个HttpRequest,这个用于比较复杂的Post请求
1、普通表单请求:
Map<String, Object> body = new HashMap<>();
body.put("username", "username");
body.put("password", "password");
String urlData= HttpRequest.post(url)
//头信息,多个头信息多次调用此方法即可
.header("tenantId", tenantId)
.header("channelId", channelId)
.header("secretKey", secretKey)
//表单内容
.form(paramMap)
.timeout(20000)
.execute()
.body();
//拿到返回值是String 转成对象
Response response = (Response) JsonUtil.json2Object(urlData, Response.class);
2、JSON格式请求:
JSONObject param = new JSONObject();
param.put("merchant_identification", merchantId);
param.put("bill_date", date);
String urlData = HttpRequest.post(uUrl)
//头信息,多个头信息多次调用此方法即可
.header("tenantId", tenantId)
.header("channelId", channelId)
.header("secretKey", secretKey)
//JSON数据
.body(param.toJSONString())
.timeout(20000)
.execute()
.body();
//拿到返回值是String 转成对象
Response response = (Response) JsonUtil.json2Object(urlData, Response.class);