java HTTP POST 请求


 此前用其他方式写 会遇到这个问题 : PKIX path building failed

 

后来统一的写法:

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class ShukeUtil {

private static final Logger logger = LogManager.getLogger(ShukeUtil.class);
private long TIME_GAP;
private int TYPE = 3;
private String password;
private String username;
private String shukeUrl;
private HashMap<String, String> orgIdMap;
private boolean logTag = false ;


public String getToken() {
// token 已经有了,并且 在有效期内,直接返回
if (tokenMap.get("token") != null) {
long now = System.currentTimeMillis();
long timeStamp = Long.parseLong(tokenMap.get("timeStamp"));
long timeGap = Math.abs(now - timeStamp);
if (timeGap < TIME_GAP) {
logger.info(" The last token is still effective... ");
return tokenMap.get("token");
}
}
logger.info("Getting the token ");
// token 不在有效期内,基于账号密码去请求获取 Token
String url = shukeUrl + "/api/auth/login";
if(logTag){logger.info("url-1 : "+ url );}

JSONObject json = new JSONObject();
json.put("password", password);
json.put("username", username);
if(logTag){logger.info("request body for getting token : "+json);}

HashMap<String ,String > headers = new HashMap<>();
headers.put("Content-type", "application/json");
if(logTag){logger.info("request headers for getting token : "+headers);}

String response = sendHttpPost( url, json , headers);
if(logTag){logger.info("login response : "+response);}

// 根据 返回内容 获取 token
ShukeResultEntity responseEntity = JSONObject.parseObject(response, ShukeResultEntity.class);
String token = responseEntity.getToken();
if(token!=null){
logger.info("Get token successful ");
}else{
logger.info("Get token failed ");
}
// 更新 token map
tokenMap.put("token", token);
tokenMap.put("timeStamp", System.currentTimeMillis() + "");
return token;
}

public String getInfo(String orgId, String assertId, String points) {
String shukeOrgId = orgIdMap.get(orgId);
String url = shukeUrl + "?orgId=" + shukeOrgId;
if(logTag){logger.info("url-2 : " + url); }

// 构造请求体 jsonStr json 格式
JSONObject json = new JSONObject();
json.put("mdmids", assertId);
json.put("points", points);
if(logTag){logger.info("request body : "+ json);}

// 获取到 token
String subToken = getToken();
if(logTag){logger.info("subToken : "+ subToken);}

// 构造请求头
HashMap<String, String> headers = new HashMap<>();
headers.put("X-Authorization", "Bearer " + subToken);
headers.put("Content-type", "application/json");
logger.info("request header : "+ headers);
String response = null;

response = sendHttpPost(url, json, headers);
if(logTag){logger.info("response : "+ response);}
logger.info("response : "+ response);
return response;
}


public static String sendHttpPost(String url, JSONObject json , HashMap<String ,String > headers) {
String jsonStr = json.toString();
HttpPost post = new HttpPost(url);
String response = "";
RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000)
.setConnectTimeout(10000).setSocketTimeout(10000).build();
CloseableHttpClient client = null;
try {
client = HttpClients.custom().setDefaultRequestConfig(config)
.setSslcontext(SSLContexts.custom().loadTrustMaterial(null, (x509Certificates, s) -> true).build())
.setMaxConnTotal(500)
.setMaxConnPerRoute(200).build();
for(Map.Entry<String,String> entry : headers.entrySet() ){
post.addHeader(entry.getKey(), entry.getValue());
}
StringEntity requestBody = new StringEntity( jsonStr, "utf-8");
post.setEntity(requestBody);
CloseableHttpResponse httpResponse = client.execute(post);
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
strber.append(line + "\n");
}
inStream.close();
response = strber.toString();
} catch (Exception e) {
logger.info(e.getStackTrace());
} finally {
try {
client.close();
} catch (Exception e) {
logger.info(e.getStackTrace());
}
}
return response;
}
}

 


免责声明!

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



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