importorg.apache.http.HttpEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;import javax.net.ssl.*;import java.io.*;importjava.net.URL;importjava.net.URLConnection;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;public classHttpPost {public staticString sendHttpsPost(String url, String params){
DataOutputStream out= null;
BufferedReader in= null;
StringBuffer result= newStringBuffer();
URL u= null;
HttpsURLConnection con= null;//尝试发送请求
try{
SSLContext sc= SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { newHttpPost.TrustAnyTrustManager() },newjava.security.SecureRandom());
u= newURL(url);//打开和URL之间的连接
con =(HttpsURLConnection)u.openConnection();//设置通用的请求属性
con.setSSLSocketFactory(sc.getSocketFactory());
con.setHostnameVerifier(newHttpPost.TrustAnyHostnameVerifier());//con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json"); // con.setUseCaches(false);//发送POST请求必须设置如下两行
con.setDoOutput(true);
con.setDoInput(true);
con.connect();
out= newDataOutputStream(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();
}
}returnresult.toString();
}public staticString sendHttpPost(String url, String body) {
String result= "";
OutputStreamWriter out= null;
BufferedReader in= null;try{
URL realUrl= newURL(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(newInputStreamReader(
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();
}
}returnresult;
}private static class TrustAnyTrustManager implementsX509TrustManager {public voidcheckClientTrusted(X509Certificate[] chain, String authType)throwsCertificateException {
}public voidcheckServerTrusted(X509Certificate[] chain, String authType)throwsCertificateException {
}publicX509Certificate[] getAcceptedIssuers() {return newX509Certificate[] {};
}
}private static class TrustAnyHostnameVerifier implementsHostnameVerifier {public booleanverify(String hostname, SSLSession session) {return true;
}
}public staticString httpPostWithJSON(String url, String json)
{//创建默认的httpClient实例
CloseableHttpClient httpclient =HttpClients.createDefault();
String str= null;try{//创建httppost
org.apache.http.client.methods.HttpPost httppost = neworg.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());
}
}returnstr;
}
}