远程部署项目,修改catalina.bat文件 完美解决在代理服务器上HttpURLConnection 调接口超时的问题

远程给客户部署项目,运行时程序调外部接口时总是出不去,经过不懈努力,后来发现客户那边的网络走的是代理,于是在代码中加下面代码:

//设置代理  
System.setProperty("http.proxySet", "true");  
System.setProperty("http.proxyHost", "代理ip地址");  
System.setProperty("http.proxyPort", "8080");  

调试后,汗~~~不管用,又开始找资料,请教别人后才知道 只要在Tomcat的..\bin\catalina.bat文件里添加代理就可以了

找到set JAVA_OPTS加上如下代码即可:

set JAVA_OPTS=%JAVA_OPTS% -server -XX:PermSize=128M -XX:MaxPermSize=512m -Dhttp.proxyHost=代理服务器ip -Dhttp.proxyPort=代理服务器端口 -Dhttps.proxyHost=代理服务器ip -Dhttps.proxyPort=代理服务器端口 

 心想这下应该可以正常运行了吧,结果还是超时,最后干脆用java的原始类HttpURLConnection替换掉第三方开源框架类HttpClient,运行后,OK ! ! ! ~

以下是部分代码:

package com.bwdz.fp.saas.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

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

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;


public class HttpsFptClient {
    private static Logger logger = Logger.getLogger(CYInterface.class);
    private static TrustManager myX509TrustManager = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {

        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {

        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    };
    public static String doPost(String url,Map<String,String> map,String charset){  
        HttpClient httpClient = null;  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            /*httpClient = new SSLClient();  
            httpClient.getParams().setIntParameter("http.socket.timeout",120000);  
            httpPost = new HttpPost(url);  
            //设置参数  
            List<NameValuePair> list = new ArrayList<NameValuePair>();  
            Iterator iterator = map.entrySet().iterator();  
            while(iterator.hasNext()){  
                Entry<String,String> elem = (Entry<String, String>) iterator.next();  
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
            }  
            if(list.size() > 0){  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);  
                httpPost.setEntity(entity);  
            }  
            HttpResponse response = httpClient.execute(httpPost);  
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,charset);  
                }  
            }  */
            
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{myX509TrustManager},
                    null);

            URL console = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();

            int timeout = 30000;
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
            conn.setSSLSocketFactory(sslcontext.getSocketFactory());
            //conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            
            conn.connect();
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            String requestData = parseParams(map);
            out.write(requestData.getBytes(charset));
            // 刷新、关闭
            out.flush();
            out.close();
            
            String responeStr = readStream(conn.getInputStream());
            return responeStr;
        } catch (Exception e) {
            logger.error("https post error: " + e.getMessage()+",url:"+url);
            return null;
        }
    }  
    
    /**
     * 将map转为字符串
     *
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String parseParams(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            stringBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8"));
            stringBuilder.append("=");
            stringBuilder.append(URLEncoder.encode(entry.getValue() == null ? "" : entry.getValue(), "utf-8"));
            stringBuilder.append("&");
        }
        String str = stringBuilder.toString();
        if (str.length() > 0) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }
    
    /**
     * 读取流
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static String readStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));  
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        return sb.toString();
    }
}

 

posted @ 2018-01-08 15:23  酸牛奶  阅读(918)  评论(0编辑  收藏  举报