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.

23
  • have you check webservices?are they working fine? Commented Apr 21, 2015 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? Commented Apr 21, 2015 at 10:10
  • @ImtiyazKhalani Yes webservices are working well,I can check them from RestApi client provided by google Chrome Commented Apr 21, 2015 at 10:20
  • @greenapps The url on emulator and the device are the same Commented Apr 21, 2015 at 10:21
  • 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? Commented Apr 21, 2015 at 17:07

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

2 Comments

I am looking into it.
It seems it didn't work out. Did you exclude the possibility of DNS problem, by putting in IP instead of domain?
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 +
            '}';
    }
}

2 Comments

why dont u use AsyncTask, this is related to the thread safe issue
Please refer to the code snippet attached with the question, I am already using AsyncTask
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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.