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