Java:http的post请求(带参数json格式)示例代码:
undefined
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 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();
}
Original: https://www.cnblogs.com/lizm166/p/16143017.html
Author: 整合侠
Title: Java:http的post请求(带参数json格式)示例代码
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/537725/
转载文章受原作者版权保护。转载请注明原作者出处!