請參閱此代碼。它將幫助您理解處理幾乎所有基本的HttpClient異常。 嘗試{
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
// new
HttpParams httpParameters = httpPost.getParams();
// Set the timeout in milliseconds until a connection is
// established.
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams
.setSoTimeout(httpParameters, timeoutSocket);
// new
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
// new
HttpParams httpParameters = httpGet.getParams();
// Set the timeout in milliseconds until a connection is
// established.
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams
.setSoTimeout(httpParameters, timeoutSocket);
// new
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
throw new Exception("Unsupported encoding error.");
} catch (ClientProtocolException e) {
throw new Exception("Client protocol error.");
} catch (SocketTimeoutException e) {
throw new Exception("Sorry, socket timeout.");
} catch (ConnectTimeoutException e) {
throw new Exception("Sorry, connection timeout.");
} catch (IOException e) {
throw new Exception("I/O error(May be server down).");
}
可能是你的服務器沒有回答? – njzk2 2013-05-03 08:21:55
您的服務器是否在默認端口上偵聽?如果不。你有沒有指定端口?您的服務器是否在Web瀏覽器上正確回答請求?你期待什麼樣的迴應? – 2013-05-03 08:25:46