如何设置android HttpPost 连接服务器超时
4个回答
2015-01-18
展开全部
// 根据内容来源地址创建一个Http请求
HttpPost request = new HttpPost(SERVER_URL);
//设置请求超时
int timeoutConnection = 3 * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
//设置响应超时
int timeoutSocket = 5 * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// 发送请求并获取反馈
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = httpClient.execute(request);
HttpPost request = new HttpPost(SERVER_URL);
//设置请求超时
int timeoutConnection = 3 * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
//设置响应超时
int timeoutSocket = 5 * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// 发送请求并获取反馈
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = httpClient.execute(request);
追答
如何设置android HttpPost 连接服务器超时
代码如下:
Java code
public static String post(String url,String json) { /* HTTP Post */ HttpPost httpRequest = new HttpPost(url); // param NameValuePair[] // request.getParameter("name") List params = new ArrayList(); params.add(new BasicNameValuePair("jsonParameter", json)); try { // HTTP request (new UrlEncodedFormEntity(params, HTTP.UTF_8)); // HTTP response defaultHttpClient = new DefaultHttpClient(); [color=#FF0000]HttpResponse (httpRequest);[/color] // 200 ok if (().getStatusCode() == 200) { result= EntityUtils.toString(()); return result; } } catch (ClientProtocolException e) { e.printStackTrace(); return null; } return result; }
红色标记的那行:HttpResponse (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);
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
如何设置android HttpPost 连接服务器超时
代码如下:
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);
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
setconnecttimeout
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
gnbnbnbnnb
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询