JAVA遠端訪問url並傳遞JSON格式字串資料
使用org.apache.http下的工具類訪問url,並傳遞json格式的資料字串,可使用CookieStore
傳遞cookie的JSESSIONID資料,也可以為null。
public static Map sendUrlJsonData(String url, String json, CookieStore cookieStore) {Map map=new HashMap<>();
final String CONTENT_TYPE_TEXT_JSON = "text/json";
CloseableHttpClient buildSSLCloseableHttpClient = createSSLClientCookie(cookieStore);
// 設定請求和傳輸超時時間
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(30000).setConnectTimeout(30000).build();
try {
System.setProperty("jsse.enableSNIExtension", "false");
HttpPost request = new HttpPost(url);
request.setConfig(requestConfig);
request.setHeader("Content-Type", "application/json;charset=UTF-8");
stringEntity.setContentType(CONTENT_TYPE_TEXT_JSON);
request.setEntity(stringEntity);
HttpResponse httpResponse = buildSSLCloseableHttpClient.execute(request);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
map.put("data", EntityUtils.toString(httpResponse.getEntity(), "utf-8"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buildSSLCloseableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
public static CloseableHttpClient createSSLClientCookie(
CookieStore cookieStore) {
SSLContext sslContext;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null,
new TrustStrategy() {
// 信任所有
@Override
public boolean isTrusted(X509Certificate[] xcs,
String string) {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
if (cookieStore != null) {
return HttpClients.custom().setDefaultCookieStore(cookieStore)
.setSSLSocketFactory(sslsf).build();
} else {
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
} catch (Exception e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}