zoukankan      html  css  js  c++  java
  • HttpUtil

    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;
    	}
    }
    

      

  • 相关阅读:
    剑指offer:二分查找找到旋转数组中的最小值
    强制索引
    剑指offer:青蛙跳台阶
    剑指offer:求和
    序列化和反序列化
    装饰器、生成器
    Python函数(一)
    【转】C# 中的委托和事件
    【读书笔记】备忘录模式翻译成C++了
    【学习笔记】Android 调试桥
  • 原文地址:https://www.cnblogs.com/1025804158ysb/p/10043420.html
Copyright © 2011-2022 走看看