Webservice call from an Android device does not work, works well on an emulator

A few months ago, I developed several applications for Android applications, including

  • GCM functionality
  • Webservice Calls

At that time he worked well. Yesterday, I tried to run it on a real device, and I found that it could not make any webservice call . I expected the same thing on the emulator. But, to my surprise, it worked well on an emulator .....


The exception that I get on a real device is: ConnectionTimeOutException .


I want to know what went wrong to get rid of the problem. I am not sure what additional information I should post. Please ask if you want me to post something.

EDIT:

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; } 

My web service is online and I tried using different internet providers


Edit (May 4, 2015):

I do not know what caused the problem, but I did not change the code, but its work again.

+6
source share
6 answers

Two years later, going through this, I suspect that the real problem was the Wi-Fi connection due to the firewall settings that our company uses. I recommend that everyone going through this problem should check the check at their IT department because they were the culprits of the day.

0
source

nobalG, try my code

here is the JSONParser class

 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; }} 

adding this Json ref class. call webservice using the post method and pass peram as I passed the data and received the data through your webservice response.

 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) { } } } 

his work is wonderful for me. use it. it can help you.

+1
source

This is likely due to DefaultHttpClient, which is not thread safe. Browse this thread to see more details, as well as this answer for a possible solution on how to use ThreadSafeClientConnManager . Good luck and give feedback if it solves your problem.

0
source
 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

Also here is a sample code, like me for this, its for REST services, but maybe you will find something useful

 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 + '}'; } } 
0
source

It may sound a little silly, but it is always recommended to check your internet connection before trying to connect to the internet in any scenario.

Here is a simple snippet for this: Detecting if an Android device has an Internet connection

Also, try increasing the timeout value using setconnectiontimeout ().

Hope this works for you :)

0
source

The exception that I get on a real device is: ConnectionTimeOutException.

Your emulator probably uses a much faster internet connection on your desktop / laptop and the connection does not sync there.

There should be a bad connection on the mobile phone. Try increasing the connection timeout as follows:

  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); 
0
source

Source: https://habr.com/ru/post/985586/


All Articles