HttpPost,厚度模拟post提交报文
import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import javax.net.ssl.*; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpPost { public static String sendHttpsPost(String url, String params){ DataOutputStream out = null; BufferedReader in = null; StringBuffer result = new StringBuffer(); URL u = null; HttpsURLConnection con = null; //尝试发送请求 try{ SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new HttpPost.TrustAnyTrustManager() }, new java.security.SecureRandom()); u = new URL(url); //打开和URL之间的连接 con = (HttpsURLConnection)u.openConnection(); //设置通用的请求属性 con.setSSLSocketFactory(sc.getSocketFactory()); con.setHostnameVerifier(new HttpPost.TrustAnyHostnameVerifier()); //con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); // con.setUseCaches(false); //发送POST请求必须设置如下两行 con.setDoOutput(true); con.setDoInput(true); con.connect(); out = new DataOutputStream(con.getOutputStream()); out.write(params.getBytes("utf-8")); // 刷新、关闭 out.flush(); out.close(); //读取返回内容 //InputStream is = con.getInputStream(); //定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8")); String line; while((line = in.readLine()) != null) { result.append(line).append(System.lineSeparator()); } }catch(Exception e){ e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally { try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } if(con != null) { con.disconnect(); } } catch(IOException ex){ ex.printStackTrace(); } } return result.toString(); } public static String sendHttpPost(String url, String body) { String result = ""; OutputStreamWriter out = null; BufferedReader in = null; try { URL realUrl = new URL(url); URLConnection conn = realUrl.openConnection(); // 设置连接参数 conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(20000); // 提交数据 out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); out.write(body); out.flush(); // 读取返回数据 in = new BufferedReader(new InputStreamReader( conn.getInputStream(), "UTF-8")); String line = ""; boolean firstLine = true; // 读第一行不加换行符 while ((line = in.readLine()) != null) { if (firstLine) { firstLine = false; } else { result += System.lineSeparator(); } result += line; } } catch (Exception e) { e.printStackTrace(); }finally{ try { in.close(); out.close(); } catch (Exception e2) { e2.printStackTrace(); } } return result; } private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } } private static class TrustAnyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } public static String httpPostWithJSON(String url, String json) { // 创建默认的httpClient实例 CloseableHttpClient httpclient = HttpClients.createDefault(); String str = null; try { // 创建httppost org.apache.http.client.methods.HttpPost httppost = new org.apache.http.client.methods.HttpPost(url); httppost.addHeader("Content-type", "application/json; charset=utf-8"); System.out.println("executing request " + httppost.getURI()); // 向POST请求中添加消息实体 StringEntity se = new StringEntity(json, "UTF-8"); httppost.setEntity(se); System.out.println("request parameters " + json); // 执行post请求 CloseableHttpResponse response = httpclient.execute(httppost); try { // 获取响应实体 HttpEntity entity = response.getEntity(); // 打印响应状态 System.out.println(response.getStatusLine()); if (entity != null) { str=EntityUtils.toString(entity, "UTF-8"); // 打印响应内容 System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); System.out.println("--------------------------------------"); } } finally { response.close(); } } catch (Exception e) { System.out.println("executing httpPostWithJSON error: " + e.getMessage()); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { System.out.println("executing httpPostWithJSON error: " + e.getMessage()); } } return str; } }