我需要使用 apache HttpClient 包将发布数据发送到 https url,
发送帖子数据后,我需要检索 html 数据。
我发送的发布数据是一个 XML 字符串,我接收的发布数据是一个 XML 字符串。
如能提供有关此问题的任何信息,我们将不胜感激。
我用谷歌搜索并在互联网上找到了使用 DefaultHttpClient 的示例,现在在版本 4 中已弃用。所以想知道如何正确使用新版客户端。
谢谢。
更新
public String sendPost(final String request, final String postData) throws ClientProtocolException, IOException {
String result = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(request);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} finally {
response.close();
}
return result;
}
到目前为止,我想出了发送请求并从响应中检索字符串的 this 函数。我认为它应该工作。我缺少的是我没有对 postData 做任何事情。如何随请求发送帖子数据?
最佳答案
public String sendPost(final String request, final String postData) throws ClientProtocolException, IOException, NoSuchAlgorithmException, KeyManagementException {
String result = null;
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(new SSLSocketFactory(sslContext)).build();
HttpPost httpPost = new HttpPost(request);
ByteArrayEntity postDataEntity = new ByteArrayEntity(postData.getBytes());
httpPost.setEntity(postDataEntity);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} finally {
response.close();
}
return result;
}
关于java - 在没有使用 apache httpClient 客户端进行 ssl 证书验证的情况下将发布数据发送到 https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14561293/