2 y2408509787 Y2408509787 于 2014.09.17 11:56 提问

请大神们帮帮,httpResponse.getStatusLine().getStatusCode()

public String httpGet(String url, String params) throws Exception{
String response = null; //返回信息
//拼接请求URL
if (null!=params&&!params.equals("")){
url += "?" + params;
}
int timeoutConnection = 3000;
int timeoutSocket = 5000;
HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established.

HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data.

HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

// 构造HttpClient的实例
HttpClient httpClient = new DefaultHttpClient(httpParameters);

// 创建GET方法的实例
HttpGet httpGet = new HttpGet(url);
try{
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK){ //SC_OK = 200
response = EntityUtils.toString(httpResponse.getEntity());

            }
            else{
                response = "返回码:"+statusCode;
            }
        }else{
            System.out.println("--------------请求链接失败----------------");
        }
    } catch (Exception e){
        System.out.println("--Exception--");
        e.printStackTrace();
    }finally{
        // 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源 
        httpClient.getConnectionManager().shutdown();
    }
    return response;
}

每次执行httpResponse.getStatusLine().getStatusCode(),第一次执行时很容易链接失败

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!