码迷,mamicode.com
首页 > Web开发 > 详细

HttpUtil

时间:2018-11-30 13:43:09      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:str   stat   cts   string   protoc   启用   dfa   else   get   

package shjt.pay.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


public class HttpUtil {
	
	public static String callServer(String askUrl,String json){
        String str = "";
        //是否启用Https
        boolean useHttps = askUrl.startsWith("https");
        if(useHttps){
        	str = doHttps(askUrl,json);
        }else{
        	str = doHttp(askUrl,json);
        }                                   
        return str;   
    }
	
	public static String doHttp(String askUrl,String json){
        StringBuffer sb = new StringBuffer(""); //输出的结果
        try {
        	URL url = new URL(askUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);//不使用缓存
            connection.setInstanceFollowRedirects(true);//自动重定向
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            //连接
            connection.connect();
            //POST请求
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            out.write(json);
            out.flush();
            out.close();
            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes());
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
		} catch (IOException e) {			
			e.printStackTrace();
		} 
        return sb.toString();

	}
	
	public static String doHttps(String askUrl,String json){
		StringBuffer sb = new StringBuffer(""); //输出的结果
        try {
        	URL url = new URL(askUrl);
        	HttpsURLConnection  connection = (HttpsURLConnection ) url.openConnection();           
            SSLSocketFactory oldSocketFactory = null;
            HostnameVerifier oldHostnameVerifier = null;
            oldSocketFactory = trustAllHosts(connection);
            oldHostnameVerifier = connection.getHostnameVerifier();
            connection.setHostnameVerifier(DO_NOT_VERIFY);			
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);//不使用缓存
            connection.setInstanceFollowRedirects(true);//自动重定向
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            //连接
            connection.connect();
            //POST请求
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            out.write(json);
            out.flush();
            out.close();
            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes());
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
		} catch (IOException e) {			
			e.printStackTrace();
		} 
        return sb.toString();
	}
	
	/**
	 * 覆盖java默认的证书验证
	 */
	 private static final TrustManager[] trustAllCerts = new TrustManager[]{
		 new X509TrustManager() {
			 
			 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
	            return new java.security.cert.X509Certificate[]{};
			 }

			 public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {
		 
			 }

			 public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {
		 
			 }
		 }
	};

	 /**
	  * 设置不验证主机
	  */
	 private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
	        public boolean verify(String hostname, SSLSession session) {
	            return true;
	        }
	 };
		
	/**
	  * 信任所有
	  * @param connection
	  * @return
	*/
	private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
		SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			SSLSocketFactory newFactory = sc.getSocketFactory();
			connection.setSSLSocketFactory(newFactory);
		} catch (Exception e) {
	      e.printStackTrace();
		}
		return oldFactory;
	}
}

  

HttpUtil

标签:str   stat   cts   string   protoc   启用   dfa   else   get   

原文地址:https://www.cnblogs.com/1025804158ysb/p/10043420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!