1

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?
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
Vishal Vijay
  • 2,518
  • 2
  • 23
  • 45
  • 4
    Please can you post some code with logcat? – GrIsHu Jan 04 '13 at 10:15
  • You need to check a lot of things while connecting to remote server. Checking only the internet connection is not sufficient as a whole. Post code along with logcat output. – Kanth Jan 04 '13 at 10:16
  • 3
    `Getting a force close sometimes because of sudden death of Internet connection after making http request.` - Always set a Connection and Socket Time Out for your Http Request, and Handle that Exception is the best way.. – user370305 Jan 04 '13 at 10:17
  • yeah i hope @user370305 correct and u should check the internet connection and then make sure you have proper exception handling – Vivek Bajpai Jan 04 '13 at 10:19
  • how do I set socket time out...is there any pre defined functions.. or should I do it manually.. – Vishal Vijay Jan 04 '13 at 10:20
  • 1
    Look at http://stackoverflow.com/questions/3075506/http-connection-timeout-on-android-not-working – user370305 Jan 04 '13 at 10:21
  • ya @user370305 may be this is what I'm asking for... I will test that... Thanks – Vishal Vijay Jan 04 '13 at 10:31
  • You can set the Connection Time out in your Http request. If your request timed out it will give you TimeOut Exception and you need to handle that and can do necessary things. – Scorpion Jan 04 '13 at 10:38

2 Answers2

5

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);
dsrees
  • 6,116
  • 2
  • 26
  • 26
Farooq
  • 426
  • 2
  • 12
0

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);
Payal
  • 903
  • 1
  • 9
  • 28