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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM