程序员的资源宝库

网站首页 > gitee 正文

Java:http的post请求(带参数json格式)示例代码

sanyeah 2024-04-12 17:40:06 gitee 3 ℃ 0 评论

Java:http的post请求(带参数json格式)示例代码:


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;


public
JSONObject sendPost(String url, LoginSsoReq req){ HttpResponse httpResponse = null; try { JSONObject json=new JSONObject(); json.put("client_id",req.getClientId()); json.put("grant_type",req.getGrantType()); json.put("code",req.getCode()); json.put("remote_ip",req.getRemoteIp()); json.put("redirect_uri",req.getRedirectUri()); // 设置请求头 Map<String, String > heads = new HashMap<>(); heads.put("Content-Type", "application/json;charset=UTF-8"); httpResponse = HttpRequest.post(url) // url .headerMap(heads, false) // 请求头设置 .body(json.toJSONString()) // json参数 .timeout(5 * 60 * 1000) // 超时 .execute(); // 请求 log.info("获取返回服务器的状态码:----- " + httpResponse.getStatus() ); if(httpResponse.getStatus() == 200){ //成功后响应数据 String result = httpResponse.body(); JSONObject jsonResult = JSONObject.parseObject(result); log.info("接口返回数据:"+jsonResult.toString()); return jsonResult; } } catch (Exception e) { e.printStackTrace(); } finally{ try { //释放连接 if(httpResponse != null){ httpResponse.close(); } } catch (Exception e) { e.printStackTrace(); } } return new JSONObject(); }

 

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表