Hutool - HttpUtil发送GET、POST请求

引入Hutool依赖

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

GET

发起get请求

@ApiOperation(value = "API描述")
@GetMapping("/xx/xxxxxx")
@ResponseBody
public Object getIssueTypeListClassBMenu(@PathVariable String service,@RequestParam(value = "cookie", defaultValue = "") String cookie) {
  String url = "http://xx.xx.xx/api/v1/" + service + "/baidu/getBaiduBMenu";
  HttpRequest get = HttpUtil.createGet(url);
  // 如果有cookie 或者token进行鉴权,可以在此添加
  get.header("cookie",cookie);
  String body = get.execute().body();
  return JSONArray.parseArray(body);
}

POST

准备工作

创建实体 - 大
package xx.xxx.xxx.server.models;

import lombok.Data;

/**
 * @author xxxx
 */
@Data
public class ReportSubmitRequest {
	private String cookie;
   	private PrivateSubmitVO formData;
}


创建实体 - 小
package xx.xxx.xxx.xxx.models.vo;

import lombok.Data;

/**
 * @author xxxx
 */
@Data
public class PrivateSubmitVO {
	private String bugDescription;
	
	private String bugType;
	
	private String userName;
	
	private Long projectId;
	
	private String title;
	
	private String clusterName;

}

发起post请求

@ApiOperation(value = "API描述")
@PostMapping("/xxx/xxxxx")
@ResponseBody
public Object reportSubmit(@PathVariable String service, @RequestBody ReportSubmitRequest request) {
	//创建json对象作为requestBody
	PrivateSubmitVO paramMap = request.getFormData();
	JSONObject jsonObject = new JSONObject();
	jsonObject.put("bugDescription",paramMap.getBugDescription());
	jsonObject.put("bugType",paramMap.getBugType());
	jsonObject.put("userName",paramMap.getUserName());
	jsonObject.put("projectId",paramMap.getProjectId());
	jsonObject.put("title",paramMap.getTitle());
	jsonObject.put("clusterName",paramMap.getClusterName());
	// 添加请求头信息
	Map<String, String > heads = new HashMap<>();
	// 使用json发送请求,下面的是必须的
	heads.put("Content-Type", "application/json;charset=UTF-8");
	// 如果有cookie 或者token进行鉴权,可以在此添加
	heads.put("cookie",request.getCookie());
	/**
	** headerMap是添加的请求头,
	body是传入的参数,这里选择json,后端使用@RequestBody接收
	*/
	String urlStr = "http://xx.xxx.xxx.xxx/api/v1/" + service+ "/report/submit";
	return getObject(jsonObject, heads, urlStr);
    }

结语

Hotool不仅仅只有这个一种工具类,还包含了其他许多工具类,具体可以详细看我另外一篇文章
Hutool工具类 -集常用工具类为一体 - 工具类之大成
,也可以访问官方文档

在这里我作为一名Hutool的用户,我感谢Hutool的创作者和维护者们为我们带来如此强大便捷的工具库,希望Hutool功能越来越完善,为我们的开发工作带来更多的便利。同时也祝愿所有开发者没有BUG困扰,能够愉快地编写出高效、功能完善的程序。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值