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(),第一次执行时很容易链接失败