Question

I am making a HTTP request to a cgi php server from android application to get json reponse. My application is validating whether the Internet connection is available or not before making HTTP request. Upto this all things are working properly. The problem is I'm getting force close sometimes because of sudden death of Internet connection after making HTTP request.

So my questions are

  1. How do I understand I got a response from server?
  2. Should I need to keep a timmer for the response?
Was it helpful?

Solution

here is my perfect running code for web requests handling

public JSONObject connectToService(String url, final Context context ) {

    try {
        if(!isConnected(context)){
            return;
        }

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpParams httpParameters = httpGet.getParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 7500;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 7500;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream is = httpEntity.getContent();

        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");
        }
        is.close();

        String jsonString = sb.toString();
        Log.e("WebServiceHandler", "JSON string returned is"+jsonString.toString());

        JSONObject jsonObject = new JSONObject(jsonString);
        return jsonObject;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
    } catch (ConnectTimeoutException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

      return null;
}

public boolean isConnected(Context context) {
    ConnectivityManager connMgr = (ConnectivityManager) 
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    } else {
        return false;
    }
}

this code is for GET requests, if you want to hit url with POST request then simply change this line accordingly

HttpGet httpGet = new HttpGet(url);

with

HttpPost httpPost = new HttpPost(url);

OTHER TIPS

first of all make all your HTTP process as asyncTask because it might ANR(Application Not Responding) force close due to slow connectivity,then do proper exceptional handling. Server Response can be checked by using following code :

    HttpClient httpclient = new DefaultHttpClient(httpParameters);

        HttpGet httpget = new HttpGet(url + encodedData);

        response = httpclient.execute(httpget);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top