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

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(); }

 

posted @ 2022-04-14 09:00  整合侠  阅读(3619)  评论(0编辑  收藏  举报