出现SocketTimeoutException后一直无法在连接服务器
阅读原文时间:2023年07月09日阅读:1

在做接入sdk功能的时候,经常出现一个问题,内网向外网服务器建立连接并发送数据经常会报SocketTimeoutException这个错误,且一旦出现便大几率再也连不上了。修改之前的代码为:

public static String httpPost(String url, Map<String, String> paramMap, int timeout)  
        throws HttpException, IOException {

    List<NameValuePair> valueList = new ArrayList<NameValuePair>();  
    Iterator<String> it = paramMap.keySet().iterator();  
    while (it.hasNext()) {  
        String key = it.next();  
        String value = paramMap.get(key);  
        NameValuePair nv = new NameValuePair(key, value);  
        valueList.add(nv);  
    }

    NameValuePair\[\] valueArray = valueList.toArray(new NameValuePair\[0\]);

    String response = null;  
    HttpClient client = new HttpClient();  
    client.getParams().setCookiePolicy(CookiePolicy.IGNORE\_COOKIES);

    setTimeout(client, timeout);

    PostMethod method = new PostMethod(url);

    method.getParams().setContentCharset("UTF-8");  
    method.setRequestBody(valueArray);

    int status = client.executeMethod(method);  
    if (status != HttpStatus.SC\_OK) {  
        return response;  
    }

    response = method.getResponseBodyAsString();

    return response;  
}

查了一些资料,试着捕获异常后,清空连接池解决,修改后的代码为:

public static String httpPost(String url, Map paramMap, int timeout)
throws HttpException, IOException {
String response = " null ";
HttpClient client = new HttpClient();
try{
List valueList = new ArrayList();
Iterator it = paramMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value = paramMap.get(key);
NameValuePair nv = new NameValuePair(key, value);
valueList.add(nv);
}

        NameValuePair\[\] valueArray = valueList.toArray(new NameValuePair\[0\]);

        client.getParams().setCookiePolicy(CookiePolicy.IGNORE\_COOKIES);

        setTimeout(client, timeout);

        PostMethod method = new PostMethod(url);

        method.getParams().setContentCharset("UTF-8");  
        method.setRequestBody(valueArray);

        int status = client.executeMethod(method);  
        if (status != HttpStatus.SC\_OK) {  
            return response;  
        }

        byte\[\] res = method.getResponseBody();//.getResponseBodyAsString();  
        response = new String(res);  
    }catch(Exception e){  
        closeIdleSocket(client);  
        throw(e);  
    }  
    return response;  
}

public static void closeIdleSocket(HttpClient client){  
    client.getHttpConnectionManager().closeIdleConnections(50000);  
}

目前这样修改之后暂时没有在出现连接超时问题了,但无法确认这个就是根源所在,所以还在持续验证中。