蝈蝈大王

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 该问题的解决办法   1、在请求前需要将证书导入,不推荐       2、绕开安全协议处理 

下面的代码时一段http请求并且绕开安全协议。可直接使用

/**
     * 
     * @param url   需要请求的网关路径
     * @param sendData  请求时需要传入的参数
     * @param urlencode url的编码格式
     * @param connTimeOut   链接超时时间 
     * @param readTimeOut   读取超时时间
     * @param contentType   请求头部  固定输入"application/x-www-form-urlencoded;charset="+urlencode
     * @param header     输入null
     * @return
     */
    public static String sendAndRcvHttpPostBase(String url,String sendData,String urlencode,int connTimeOut,int readTimeOut,String contentType,Map<String,String> header){
        Long curTime = System.currentTimeMillis();
        Trace.logInfo(Trace.COMPONENT_HTTP, "SimpleHttpConnUtil Prepare @"+curTime);
        String result = "";
        BufferedReader in = null;
        DataOutputStream out = null;
        int code = 999;
        HttpsURLConnection httpsConn = null;
        HttpURLConnection httpConn = null;
        try{
            URL myURL = new URL(url);
            Trace.logInfo(Trace.COMPONENT_HTTP, "请求地址:"+url);
            if(url.startsWith("https://")){
                httpsConn =    (HttpsURLConnection) myURL.openConnection();
                TrustManager[] trustAllCerts = new TrustManager[]{
                        new X509TrustManager() {
                            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                return null;
                            }
                            public void checkClientTrusted(
                                java.security.cert.X509Certificate[] certs, String authType) {
                            }
                            public void checkServerTrusted(
                                java.security.cert.X509Certificate[] certs, String authType) {
                            }
                        }
                    };
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                httpsConn.setSSLSocketFactory(sc.getSocketFactory());
                HostnameVerifier hv = new HostnameVerifier() {
                    @Override
                    public boolean verify(String urlHostName, SSLSession session) {
                        return true;
                    }
                }; 
                httpsConn.setHostnameVerifier(hv);
                    
                httpsConn.setRequestProperty("Accept-Charset", urlencode);
                httpsConn.setRequestProperty("User-Agent","java HttpsURLConnection");
                if(header!=null){
                    for(String key:header.keySet()){
                        httpsConn.setRequestProperty(key, (String)header.get(key));
                    }
                }
                httpsConn.setRequestMethod("POST");
                httpsConn.setUseCaches(false);
                httpsConn.setRequestProperty("Content-Type",contentType); 
                httpsConn.setConnectTimeout(connTimeOut);
                httpsConn.setReadTimeout(readTimeOut);
                httpsConn.setDoInput(true);
                httpsConn.setInstanceFollowRedirects(true); 
                if(sendData !=null){
                    httpsConn.setDoOutput(true);
                    // 获取URLConnection对象对应的输出流
                    out = new DataOutputStream(httpsConn.getOutputStream());
                    // 发送请求参数
                    out.write(sendData.getBytes(urlencode));
                    // flush输出流的缓冲
                    out.flush();
                    out.close();
                }
                // 取得该连接的输入流,以读取响应内容
                in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(),urlencode));
                code = httpsConn.getResponseCode();
            }else{
                httpConn =    (HttpURLConnection) myURL.openConnection();
                httpConn.setRequestProperty("Accept-Charset", urlencode);
                httpConn.setRequestProperty("user-agent","java HttpURLConnection");
                if(header!=null){
                    for(String key:header.keySet()){
                        httpConn.setRequestProperty(key, (String)header.get(key));
                    }
                }
                httpConn.setRequestMethod("POST");
                httpConn.setUseCaches(false);
                httpConn.setRequestProperty("Content-Type",contentType); 
                httpConn.setConnectTimeout(connTimeOut);
                httpConn.setReadTimeout(readTimeOut);
                httpConn.setDoInput(true);
                httpConn.setInstanceFollowRedirects(true); 
                if(sendData !=null){
                    httpConn.setDoOutput(true);
                    // 获取URLConnection对象对应的输出流
                    out = new DataOutputStream(httpConn.getOutputStream());
                    // 发送请求参数
                    out.write(sendData.getBytes(urlencode));
                    // flush输出流的缓冲
                    out.flush();
                    out.close();
                }
                // 取得该连接的输入流,以读取响应内容
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),urlencode));
                code = httpConn.getResponseCode();
            }
            if (HttpURLConnection.HTTP_OK == code){ 
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                    
                    
                    System.out.println("=====反回结果====="+ line);
                    
                    
                }
                if(result.length()>2000){
                    Trace.logInfo(Trace.COMPONENT_ACTION, "http返回结果 !\n"+result.substring(0,2000)+"...");
                }else{
                    Trace.logInfo(Trace.COMPONENT_ACTION, "http返回结果 !\n"+result);
                }
            }else{
                result = null;
                throw new Exception("支付失败,服务端响应码:"+code);
            }
        }catch(IOException e){
            Trace.logError(Trace.COMPONENT_ACTION, "http通讯失败 !",e);
            result = null;
        }catch(Exception e){
            Trace.logError(Trace.COMPONENT_ACTION, "http通讯失败 !",e);
            result = null;
        }finally{
            Trace.logInfo(Trace.COMPONENT_ACTION,"对方地址:"+url);
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
            if(httpConn!=null){
                httpConn.disconnect();
            }
            if(httpsConn!=null){
                httpsConn.disconnect();
            }
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
        Trace.logInfo(Trace.COMPONENT_HTTP, "SimpleHttpConnUtil "+curTime+" end for "+(System.currentTimeMillis()-curTime)+"ms");
        return result;
    }

以上代码中使用的java类的包路径,只有涉及到安全协议的包路径。

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

 

posted on 2017-03-08 15:17  蝈蝈大王  阅读(14563)  评论(2编辑  收藏  举报