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