7

I have developed some android application project a few months ago,It includes,

  • GCM functionality
  • Webservice Calls

It was working well at that time.Yesterday I tried to run it on a real device and I found that it was not able to make any webservice call. I was expecting the same on the emulator.But to my surprise it was working well on the emulator.....


The exception I am getting on the real device is: ConnectionTimeOutException.


I want to know that what went wrong to get rid of the issue.I am not sure what more 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 running on the internet and I tried using different ISP's


Edit(4th May 2015):

I don't know what caused the issue, but I haven't changed any code, but its working again.

nobalG
  • 4,798
  • 3
  • 29
  • 63
  • have you check webservices?are they working fine? – Imtiyaz Khalani Apr 21 '15 at 10:05
  • You have to post the used url/ip address. Which one did you use on the emulator and which on the device? And where is your service running? – greenapps Apr 21 '15 at 10:10
  • @ImtiyazKhalani Yes webservices are working well,I can check them from RestApi client provided by google Chrome – nobalG Apr 21 '15 at 10:20
  • @greenapps The url on emulator and the device are the same – nobalG Apr 21 '15 at 10:21
  • You are not answering all my questions. That makes it impossible to help you further. – greenapps Apr 21 '15 at 10:37
  • Would you please provide some code? Are you using DefaultHttpClient? – Plamen Petrov Apr 21 '15 at 10:59
  • @PlamenPetrov yes,I am using DefaultHttpClient, Added some code in the question. – nobalG Apr 21 '15 at 11:00
  • might be problem with internet connection speed.try with some other internet connection. – Imtiyaz Khalani Apr 21 '15 at 14:04
  • @ImtiyazKhalani I already tried this... :/ – nobalG Apr 21 '15 at 16:19
  • `And where is your service running? ` 6 hours ago I asked that already. `Please ask if you want me to post something`. You really mean that? – greenapps Apr 21 '15 at 16:55
  • With all due respect, I can't make the URL public, but I know that they are working well as I have tested them from API Client provided by Google Chrome and also successfully made call from the emulator.I am using POST method,I have deployed my REST API on JBOSS SERVER and accessing it through public IP....... nd yes I MEANT IT.. :)... @greenapps – nobalG Apr 21 '15 at 17:04
  • 3
    You do not have to publish the complete url. What i wanted to know is where your service is running. So you could answer 'somewhere on the internet'. Or it runs on my laptop/computer and the emulator is on the same computer. SO it is a public IP. Well that is strange that it does not work. Your device connects through wifi using the same router as the pc where the emulator is running on? – greenapps Apr 21 '15 at 17:07
  • Does it fail using mobile connection? Does it fail using wifi? – greenapps Apr 21 '15 at 17:11
  • You tried Chrome you said. But did you try with Chrome browser on your device? – greenapps Apr 21 '15 at 17:13
  • Failed using mobile connection,and I never used chrome from device,,,and wa,wa,wait... I said that the same application was working fine few months back(either on emulator or real device),but the issue came up,when i tried it yesterday..... @greenapps – nobalG Apr 21 '15 at 18:16
  • Normally when a device is not able to make a web service call and on the emulator it is working normally, there's a high chance that your web service is running on that same computer where the emulator was tested. One more detail is still missing in your infos: is your web service running "somewhere on the internet" or on your local machine? – CAS Apr 24 '15 at 07:33
  • @ChadiAbouSleiman ITS ON THE INTERNET – nobalG Apr 24 '15 at 07:35
  • Hi, did you check with different device. The reason could be the Firewall rules blocking the outgoing route from the client and Firewall rules blocking the incoming route to the server – Prashanth Debbadwar Apr 29 '15 at 11:30
  • @PrashanthDebbadwar what about emulator then?\ – nobalG Apr 29 '15 at 11:36
  • There is nothing blocked on emulator. What I am trying to say is there could be the issue with that particular device. – Prashanth Debbadwar Apr 29 '15 at 11:42
  • Naaaa,I don't think so,I tried using other real devices too.@PrashanthDebbadwar – nobalG Apr 29 '15 at 11:43
  • can you compare what goes in this parameters while using device and emulator? objSendjson.put("Mobile_Number", gCountryCodeAndMobileNumber); objSendjson.put("Signature_Key", Configurations.SIGNATUREKEY); i think your webservice is doing some kind of authentication with this and not to send response in case of unable to authenticate? – Dhruv Mevada Apr 30 '15 at 06:56
  • It seems the problem with the internet connection of device as suggested by @ImtiyazKhalani as emulator is using connection of a developer PC and works fine. – MohK Apr 30 '15 at 09:10

6 Answers6

1

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;

}}

now by adding this Json class ref. call webservice using post method and pass peram as i passed and get data by your webservice responce.

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

        }
    }
}

its work fine for me. use it. its may b helpful for you.

Sameer Donga
  • 948
  • 9
  • 24
1

After two years while going through this, I suspect the real problem was the Wifi connection because of the firewall settings which our company is using. I recommend everybody going through this issue must have to run a check over their company's IT department because they were the culprits for the day.

nobalG
  • 4,798
  • 3
  • 29
  • 63
0

It's probably related to DefaultHttpClient not being thread-safe. Check out this thread to see more details and also this answer for possible solution on how to make it thread-safe using ThreadSafeClientConnManager. Good luck and give feedback if it solves your problem.

Community
  • 1
  • 1
Plamen Petrov
  • 4,669
  • 4
  • 28
  • 40
0
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Also here is a code example how i to that, its for REST services but maybe u find something usefull

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 +
            '}';
    }
}
BooNonMooN
  • 242
  • 3
  • 12
0

Might sound a bit silly, but its always advisable to check for internet connectivity before trying to connect to Internet in any scenario.

Here's a simple snippet for doing the same: Detect if Android device has Internet connection

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

Hope this works for you :)

Community
  • 1
  • 1
Abby
  • 105
  • 1
  • 1
  • 9
0

The exception I am getting on the real device is: ConnectionTimeOutException.

What's probably happening is your emulator is using the much faster internet on your desktop/laptop, and the connection is not timing out there.

On the mobile phone there must be poorer connection. Try increase the connection timeout like so:

    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);
Martin Konecny
  • 50,691
  • 18
  • 119
  • 145