代码如下:
- Java code
public static String post(String url,String json) { /* HTTP Post */ HttpPost httpRequest = new HttpPost(url); // param NameValuePair[] // request.getParameter("name") List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("jsonParameter", json)); try { // HTTP request httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // HTTP response defaultHttpClient = new DefaultHttpClient(); [color=#FF0000]HttpResponse httpResponse = defaultHttpClient.execute(httpRequest);[/color] // 200 ok if (httpResponse.getStatusLine().getStatusCode() == 200) { result= EntityUtils.toString(httpResponse .getEntity()); return result; } } catch (ClientProtocolException e) { e.printStackTrace(); return null; } return result; }
红色标记的那行:HttpResponse httpResponse = defaultHttpClient.execute(httpRequest);
如果我的serve端服务是停止的,那么在这就一直等待连接了。过很长时间后,要么走catch ,要么直接报错,程序崩溃。。
如何设置它的等待时间呀,比如让他只等5秒,超过5秒进catch 语句。。。
请高手指点
------解决方案--------------------------------------------------------
已经解决。原来是有超时设置。可以这样
BasicHttpParams httpParameters = new BasicHttpParams();
// Set the default socket timeout (SO_TIMEOUT)
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
DefaultHttpClient httpClient = new DefaultHttpClient();//http客户端
HttpPost httpPost = new HttpPost(url);