后端请求第三方接口,并json形式传输数据


private String getToken(String name, String newPw, String ip) {
Map<String,String> map = new HashMap<>();

String url = "要访问的接口";

String jsonStr = "{\"user\":\""+name+"\",\"password\":\""+newPw+"\"}";

RequestConfig config = RequestConfig.custom().setSocketTimeout(40000).setConnectTimeout(40000).setConnectTimeout(40000).build();
HttpClient httpClient;
httpClient = createCloseableHttpClient(url,config);
HttpUriRequest httpMethod = null;
HttpPost pMethod = new HttpPost(url);
pMethod.setConfig(config);


try {
//进行json的转换
pMethod.addHeader("Content-Type","application/json;charset=utf-8");
// String s = jsonObject.toString();
StringEntity entity = new StringEntity(jsonStr,ContentType.APPLICATION_JSON);
pMethod.setEntity(entity);


httpMethod = pMethod;
HttpResponse resp = httpClient.execute(httpMethod);
Integer statusCode = resp.getStatusLine().getStatusCode();
String respContent = IOUtils.toString(resp.getEntity().getContent(),"utf-8");
respContent = respContent==null?"":respContent;

System.out.println(respContent);
System.out.println(statusCode.toString());
Gson gson = new Gson();
map = gson.fromJson(respContent,map.getClass());

System.out.println("token value "+map.get("token"));


} catch (Exception e) {
e.printStackTrace();
}
return map.get("token");
}

/**
* 忽略证书的方法
* @param url
* @param config
* @return
*/
private static HttpClient createCloseableHttpClient(String url, RequestConfig config) {
HttpClientBuilder builder = HttpClients.custom();
builder.setDefaultRequestConfig(config);
if(url.startsWith("https")){
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

builder.setSSLSocketFactory(sslsf);

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}

}
return builder.build();
}

有问题可加微信联系:chanhle0109


免责声明!

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



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