当前位置 : 主页 > 编程语言 > java >

Java使用hutool工具类发送网络请求

来源:互联网 收集:自由互联 发布时间:2023-03-22
​​result = HttpUtil.createGet(​​​​"https://api.yonyoucloud.com/apis/dst/Search/search"​​​​).addHeaders(header).form(map).execute().body();​​ dependency groupIdcn.hutool/groupId artifactIdhutool-all/artifactId version

​​result = HttpUtil.createGet(​​​​"https://api.yonyoucloud.com/apis/dst/Search/search"​​​​).addHeaders(header).form(map).execute().body();​​

<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.6</version></dependency>

使用案例

1.httpUtil使用post和get请求

String url = "https://xxx/xx";//指定URLMap<String, Object> map = new HashMap<>();//存放参数map.put("A", 100);map.put("B", 200);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携带IDHashMap<String, String> headers = new HashMap<>();//存放请求头,可以存放多个请求头headers.put("xxx", xxx);//发送delete请求并接收响应数据String result= HttpUtil.createRequest(Method.DELETE, url).addHeaders(headers).execute().body();

2.Http请求-HttpRequest

本质上,HttpUtil中的get和post工具方法都是HttpRequest对象的封装,因此如果想更加灵活操作Http请求,可以使用HttpRequest。

@Testpublic 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); }

其它自定义项 同样,我们通过HttpRequest可以很方便的做以下操作:

指定请求头 自定义Cookie(cookie方法) 指定是否keepAlive(keepAlive方法) 指定表单内容(form方法) 指定请求内容,比如rest请求指定JSON请求体(body方法) 超时设置(timeout方法) 指定代理(setProxy方法) 指定SSL协议(setSSLProtocol) 简单验证(basicAuth方法)

3.如需了解更多用法请参考hutool官方文档。 2021-06-22 补充一点: 用hutool工具类做httpUtil会有坑的, 最近一次需求,用该工具类去调用第三方系统的接口,结果返参的字符串格式是xml标签形式, 很诡异;后来换成restTemplate工具类去做http请求,返回的字符串格式是json的,就没问题了!!! ———————————————— 版权声明:本文为CSDN博主「JAVA_FrankZhong」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:​​https://blog.csdn.net/qq_41903017/article/details/116529206​​

自己实现案例:

//获取广告组列表以及分页列表 过滤掉删除了的分组JSONArray campaigns = qianchuanAdPlanThirdManager.listCampaign(token, campaignFiltering);/** * 获取广告组列表 * * @param token * @return */ public JSONArray listCampaign(AccessTokenQcEntity token, JSONObject filtering) { JSONArray campaignArray = new JSONArray(); HttpRequest http = ToutiaoQianchuanUtil.createGetRequest(token, ToutiaoQianchuanUtil.listCampaign); JSONObject reqParams = new JSONObject(); reqParams.put("advertiser_id", token.getAdvertiserId()); reqParams.put("page", 1); reqParams.put("page_size", ToutiaoQianchuanUtil.PAGE_SIZE_100); if (filtering == null) { filtering = new JSONObject(); } if (StrUtil.isBlank(filtering.getString("marketing_goal"))) { filtering.put("marketing_goal", "VIDEO_PROM_GOODS"); } filtering.put("status", "ALL"); reqParams.put("filter", filtering); http.form(reqParams); log.info("获取头条广告组,请求参数{}", reqParams.toString()); JSONObject jsonObject = this.doRequest(http, 1); JSONObject data = jsonObject.getJSONObject("data"); JSONArray array = data.getJSONArray("list"); campaignArray.addAll(array); Integer total = data.getJSONObject("page_info").getInteger("total_number"); if (total > ToutiaoQianchuanUtil.PAGE_SIZE_100) { this.listCampaignPage(campaignArray, total, token, filtering); } //过滤掉已删除的组 /*for (int i = campaignArray.size() - 1; i >= 0; i--) { if (campaignArray.getJSONObject(i).getString("status").equals("DELETE")) { campaignArray.remove(i); } }*/ return campaignArray; }public static HttpRequest createGetRequest(AccessTokenQcEntity token, String url) { HttpRequest http = HttpUtil.createGet(url); http.header("Content-Type", "application/json"); http.header("Access-Token", token.getAccessToken()); return http;}private JSONObject doRequest(HttpRequest http, Integer count) { if (count > tryCount) { throw new RRException("请求重试超过" + tryCount + "次,不再重试"); } try { return ToutiaoQianchuanUtil.buildResult(http); } catch (ToutiaoQianchuanUtil.AccountAbnormalityException e) { throw new RRException("账号异常"); } catch (Exception e) { log.error("查询千川计划失败:{}", ExceptionUtil.stacktraceToString(e)); ThreadUtil.sleep(1000 * 60); log.error("查询千川计划失败,进行第{}次重试", count); count++; return this.doRequest(http, count); }}

public static JSONObject buildResult(HttpRequest request) throws AccountAbnormalityException { HttpResponse execute = request.execute(); String result = execute.body(); execute.close(); log.info("请求千川返回结果:{}", result.substring(0, Math.min(result.length(), 1000))); JSONObject jsonObject = FastJsonUtil.toJSONObject(result); Integer code = jsonObject.getInteger("code"); if (code == null || !code.equals(0)) { String message = jsonObject.getString("message"); if (message.contains(REQUEST_TOO_MANY_RESULT)) { log.error("请求千川次数过多,休眠一段时间再次请求"); ThreadUtil.sleep(1000 * 60); return buildResult(request); } else if (message.contains("No permission to operate account")) { log.error("请求千川失败,账号异常:" + message); throw new AccountAbnormalityException("请求千川失败,账号异常:" + message); } log.error("请求千川失败:{},请求参数:{}", message, JSON.toJSONString(request.form())); throw new RRException("请求千川失败:" + message); } return jsonObject;}

网友评论