我需要使用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; }