我几个月前开发了一些Android应用程序项目,它包括,
当时运行良好。昨天我尝试在真实设备上运行,我发现它无法进行任何网络服务调用。 我在模拟器上的期望与此相同。但令我惊讶的是,在模拟器上运行良好 .....
我在真实设备上获得的例外是: ConnectionTimeOutException 。
我想知道摆脱这个问题出了什么问题。我不知道我应该发布什么更多信息。请问你是否要我发帖
修改
AsyncTask<Void, Void, Boolean> gettingHttpOTP = new AsyncTask<Void, Void,Boolean>(){
HttpResponse httpresponse;
HttpClient client ;
JSONObject objSendjson;
HttpPost post ;
HttpEntity entity;
String result;
JSONObject objRetrievejson;
@Override
protected Boolean doInBackground(Void... arg0) {
client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 50000);
objSendjson = new JSONObject();
try
{
post = new HttpPost(Configurations.API_VERIFY_END_USER);
objSendjson.put("Mobile_Number", gCountryCodeAndMobileNumber);
objSendjson.put("Signature_Key", Configurations.SIGNATUREKEY);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(objSendjson.toString(), "UTF-8"));
httpresponse = client.execute(post);
entity = httpresponse.getEntity();
gHttpResponseCode=httpresponse .getStatusLine().getStatusCode();
if(gHttpResponseCode==200)
{
gResponseText = EntityUtils.toString(entity);
objRetrievejson=new JSONObject(gResponseText);
gRecievedJsonOutput=objRetrievejson.getString("Result_Output");
gRecievedJsonDescription=objRetrievejson.getString("Result_Message");
gRecievedJsonCode=objRetrievejson.getString("Result_Code");
gRecievedJsonStatus=objRetrievejson.getString("Result_Status");
}
else
{
gResponseText=null;
}
}
catch(Exception errorException)
{
Log.d("Exception generated with response code = "+gHttpResponseCode,""+
errorException);
}
return null;
}
修改(2015年5月4日):
我不知道导致这个问题的原因,但我没有更改任何代码,但它再次工作。
答案 0 :(得分:1)
nobalG,试试我的代码
这是JSONParser类
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
Log.e("param--- is:-", "" + params);
// Making HTTP request
try {
// 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));
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;
Log.e("-------------------------->", paramString.toString());
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.e("TAG", "sb.toString() >>>>>" + sb.toString());
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}}
现在通过添加这个Json类ref。使用post方法调用webservice并在我通过时传递peram并通过webservice响应获取数据。
class GetUserDetail extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Please wait Insert Record ....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show()
}
protected String doInBackground(String... params) {
try {
// json class ref. from above class
JSONParser jsonpd = new JSONParser();
String url_login = "www.xyz.com/user_login.php"; // webservice url
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("email", elogin_email
.getText().toString()));
params1.add(new BasicNameValuePair("password", elogin_pass
.getText().toString()));
JSONObject json = jsonpd.makeHttpRequest(url_login, "POST",
params1); // webservice call and json responce in json
JSONObject mainJson = new JSONObject(json.toString());
cnt = GlobalArea.successresult(mainJson);
JSONArray json_contents = mainJson.getJSONArray("Success");
for (int i = 0; i < json_contents.length(); i++) {
JSONObject e = json_contents.getJSONObject(i);
EMAIL = e.getString("email");
CUSTOMER_ID = e.getString("customer_id");
PASSWORD = elogin_pass.getText().toString();
}
} catch (JSONException e) {
}
return null;
}
protected void onPostExecute(String file_url) {
try {
pDialog.dismiss();
if (cnt == 2) {
Toast.makeText(getApplicationContext(),
"Check Email Id and Password", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(getApplicationContext(),
ToastStrings.LoginMessage, Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
}
它对我来说很好。用它。它可能对你有帮助。
答案 1 :(得分:0)
它可能与DefaultHttpClient不是线程安全的。请查看此thread以查看更多详细信息,并this answer了解如何使用ThreadSafeClientConnManager
使其成为线程安全的可能解决方案。如果能解决你的问题,祝你好运并提供反馈。
答案 2 :(得分:0)
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
这里有一个代码示例我如何使用它,它用于REST服务,但也许你找到了一些有用的东西
public class RestClient {
private final static String TAG = "RestClient";
protected Context context;
private boolean authentication;
private ArrayList<NameValuePair> headers;
private String jsonBody;
private String message;
private ArrayList<NameValuePair> params;
private String response;
private int responseCode;
private String url;
// HTTP Basic Authentication
private String username;
private String password;
public RestClient(String url) {
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
// Be warned that this is sent in clear text, don't use basic auth unless
// you have to.
public void addBasicAuthentication(String user, String pass) {
authentication = true;
username = user;
password = pass;
}
public void addHeader(String name, String value) {
headers.add(new BasicNameValuePair(name, value));
Log.i(TAG, "Header Added: " + name + " " + value);
}
public void addParam(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
public void execute(RequestMethod method) throws Exception {
switch (method) {
case GET: {
HttpGet request = new HttpGet(url + addGetParams());
request = (HttpGet) addHeaderParams(request);
executeRequest(request, url);
break;
}
case POST: {
HttpPost request = new HttpPost(url);
request = (HttpPost) addHeaderParams(request);
request = (HttpPost) addBodyParams(request);
executeRequest(request, url);
break;
}
case PUT: {
HttpPut request = new HttpPut(url);
request = (HttpPut) addHeaderParams(request);
request = (HttpPut) addBodyParams(request);
executeRequest(request, url);
break;
}
case DELETE: {
HttpDelete request = new HttpDelete(url);
request = (HttpDelete) addHeaderParams(request);
executeRequest(request, url);
}
}
}
private HttpUriRequest addHeaderParams(HttpUriRequest request)
throws Exception {
for (NameValuePair h : headers) {
request.addHeader(h.getName(), h.getValue());
}
if (authentication) {
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
username, password);
request.addHeader(new BasicScheme().authenticate(creds, request));
}
return request;
}
private HttpUriRequest addBodyParams(HttpUriRequest request)
throws Exception {
if (jsonBody != null) {
request.addHeader("Content-Type", "application/json");
if (request instanceof HttpPost)
((HttpPost) request).setEntity(new StringEntity(jsonBody,
"UTF-8"));
else if (request instanceof HttpPut)
((HttpPut) request).setEntity(new StringEntity(jsonBody,
"UTF-8"));
} else if (!params.isEmpty()) {
if (request instanceof HttpPost)
((HttpPost) request).setEntity(new UrlEncodedFormEntity(params,
HTTP.UTF_8));
else if (request instanceof HttpPut)
((HttpPut) request).setEntity(new UrlEncodedFormEntity(params,
HTTP.UTF_8));
}
return request;
}
private String addGetParams() throws Exception {
// Using StringBuffer append for better performance.
StringBuffer combinedParams = new StringBuffer();
if (!params.isEmpty()) {
combinedParams.append("?");
for (NameValuePair p : params) {
combinedParams.append((combinedParams.length() > 1 ? "&" : "")
+ p.getName() + "="
+ URLEncoder.encode(p.getValue(), "UTF-8"));
}
}
return combinedParams.toString();
}
public String getErrorMessage() {
return message;
}
public String getResponse() {
return response;
}
public int getResponseCode() {
return responseCode;
}
public void setContext(Context ctx) {
context = ctx;
}
public void setJSONString(String data) {
jsonBody = data;
}
private void executeRequest(HttpUriRequest request, String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
// Setting 15 second timeouts
HttpConnectionParams.setConnectionTimeout(params, 15 * 1000);
HttpConnectionParams.setSoTimeout(params, 15 * 1000);
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
@Override
public String toString() {
return "RestClient{" +
"authentication=" + authentication +
", headers=" + headers +
", jsonBody='" + jsonBody + '\'' +
", message='" + message + '\'' +
", params=" + params +
", response='" + response + '\'' +
", responseCode=" + responseCode +
", url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", context=" + context +
'}';
}
}
答案 3 :(得分:0)
可能听起来有点傻,但在任何情况下尝试连接到Internet之前,始终建议检查互联网连接。
以下是执行相同操作的简单代码段: Detect if Android device has Internet connection
另外,尝试使用setconnectiontimeout()增加超时值。
希望这适合你:)
答案 4 :(得分:0)
我在真实设备上获得的异常是:ConnectionTimeOutException。
可能发生的事情是您的模拟器在您的台式机/笔记本电脑上使用更快的互联网,并且连接没有超时。
在手机上必须连接较差。尝试增加连接超时,如下所示:
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
答案 5 :(得分:0)
经过两年的努力,我怀疑真正的问题是Wifi连接因为我们公司正在使用的防火墙设置。我建议所有经历这个问题的人必须对他们公司的IT部门进行检查,因为他们是当天的罪魁祸首。