Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webservice call from android device is not working,works well on emulator

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.

like image 589
nobalG Avatar asked Apr 21 '15 09:04

nobalG


People also ask

Can you make calls with an Android emulator?

Place outgoing calls from Android emulator This is simple to do in the phone UI - just press the phone icon, type in the number and call.

Can we call on emulator?

The emulator automatically forwards simulated voice calls from one instance to another. To send a voice call, use the dialer application application, respectively, from one of the emulators.

How do I fix my Android emulator?

If the emulator fails to launch due to the error vulkan-1. dll cannot be found , you probably need to update the emulator. To update the emulator in Android Studio, go to Tools > SDK Manager and install the latest stable version of Android platform.


1 Answers

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.

like image 102
Sameer Donga Avatar answered Oct 01 '22 22:10

Sameer Donga