从Android应用程序调用webservice时,我有两到三次执行。当我从2.3.3(仿真器)版本的应用程序调用web服务时,我得到异常,如UnhostException,4.2.2(真实设备)版本上的connectiontimeoutexception和3.1版本的正常工作,我不知道为什么会发生这种情况。我试图从昨天开始解决这个异常但是已经解决,如果代码中需要进行任何更改,那么请建议我。
在 LoginActivity 中,我调用了发出http请求的方法
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", userpsw));
JsonParserWebs jsonDataFromSrvr = new JsonParserWebs();
String loginData = jsonDataFromSrvr.makeHttpReqToSrvr(loginUrl,"POST", params);
以下是用于调用webservice的 JsonParserWebs
public String makeHttpReqToSrvr(String url,String requestType,List<NameValuePair> params) {
Log.i(JsonParserWebs.class.getName(),"URL..."+url);
HttpEntity httpEntity=null;
//making http request
try {
if (requestType == "GET") {
//connection time out
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
String paramString =URLEncodedUtils.format(params, "utf-8");
HttpGet httpGet = new HttpGet(url+"?"+paramString);
HttpResponse httpResp = httpClient.execute(httpGet);
httpEntity = httpResp.getEntity();
}
if (requestType == "POST") {
//connection time out
// From stackoverflow, I addes following three line but still got ConnectTimeoutException
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResp = httpClient.execute(httpPost);
httpEntity = httpResp.getEntity();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
json = EntityUtils.toString(httpEntity);
Log.v("JSON", "data"+json);
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
return json;
}
先谢谢
答案 0 :(得分:0)
您需要使用AsyncTask,否则会崩溃!
答案 1 :(得分:0)
1。使用AsyncTask时,如果您使用耗时的过程,则会出现网络异常 2。在.mainfeast
中获取互联网权限