2

I'm writing an application that connects to a webservice and I don't want it to wait too long if it can't get a connection. I therefore set the connectionTimeout of the httpparams. But it doesn't seem to have any effect whatsoever.

Here is my code (partly based on this answer by kuester2000)

public void doPost(ArrayList<NameValuePair> list) {

        HttpPost post = new HttpPost(URL);
        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 = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
                timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

        httpClient.setParams(httpParameters);
        try {
            post.setEntity(new UrlEncodedFormEntity(list));
            HttpResponse response = httpClient.execute(post);

            Log.i("response ", response.toString());

            Log.i("response code", ""
                    + response.getStatusLine().getStatusCode());

            if (response != null) {

                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    InputStream instream = entity.getContent();
                    result = convertStreamToString(instream);
                    Log.i("Result ", result);
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            } else {
                Log.i("SERVER ERROR ", "Server Not responding");
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

now i add exception

but my log cate dosent show any error within 5 second. it will give me error on 2 3 mint.

here is error

03-26 12:36:59.165: W/System.err(491): java.net.SocketException: The operation timed out
03-26 12:36:59.165: W/System.err(491):  at org.apache.harmony.luni.platform.OSNetworkSystem.connectStreamWithTimeoutSocketImpl(Native Method)
03-26 12:36:59.165: W/System.err(491):  at org.apache.harmony.luni.platform.OSNetworkSystem.connect(OSNetworkSystem.java:115)
03-26 12:36:59.165: W/System.err(491):  at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:244)
03-26 12:36:59.165: W/System.err(491):  at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:533)
03-26 12:36:59.165: W/System.err(491):  at java.net.Socket.connect(Socket.java:1055)
03-26 12:36:59.165: W/System.err(491):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-26 12:36:59.165: W/System.err(491):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
03-26 12:36:59.165: W/System.err(491):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-26 12:36:59.165: W/System.err(491):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-26 12:36:59.165: W/System.err(491):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
03-26 12:36:59.165: W/System.err(491):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-26 12:36:59.165: W/System.err(491):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-26 12:36:59.165: W/System.err(491):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-26 12:36:59.165: W/System.err(491):  at com.raa.json.JsonParser1.getJSONFromUrl(JsonParser1.java:39)
03-26 12:36:59.165: W/System.err(491):  at com.raa.activity.ProductListActivity$MyTask.doInBackground(ProductListActivity.java:168)
03-26 12:36:59.165: W/System.err(491):  at com.raa.activity.ProductListActivity$MyTask.doInBackground(ProductListActivity.java:1)
03-26 12:36:59.165: W/System.err(491):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-26 12:36:59.165: W/System.err(491):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-26 12:36:59.165: W/System.err(491):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-26 12:36:59.165: W/System.err(491):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
03-26 12:36:59.165: W/System.err(491):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
03-26 12:36:59.165: W/System.err(491):  at java.lang.Thread.run(Thread.java:1096)
Ryan M
  • 18,333
  • 31
  • 67
  • 74
vivek tiwari
  • 645
  • 3
  • 10
  • 23

2 Answers2

4

Try this ,private static long TIME_OUT_IN_SECONDS = 120;

          System.out.println("posthhhhhhhhhhhhhhhhhhh");

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = null;
        long requestStratTime = new Date().getTime();

        httpResponse = httpClient.execute(httpPost);
        long requestEndTime = new Date().getTime();
        Log.d("requestStratTime", "requestStratTime" + requestStratTime);
        Log.d("requestEndTime", "requestEndTime" + requestEndTime);
        long timeOfRequest = (requestEndTime - requestStratTime) / 1000;
        Log.d("timeOfRequest", "timeOfRequest" + timeOfRequest);
        if (httpResponse == null && timeOfRequest > TIME_OUT_IN_SECONDS) {

            throw new TimeOutException();
        }

        int responseCode = httpResponse.getStatusLine().getStatusCode();
        System.out.println("responseCode" + responseCode);
        String ss = httpResponse.getStatusLine().toString();
        System.out.println("ssssssssssssssssssssssss" + ss);
        if (responseCode == 200) {

            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else {
            throw new ParsingException();
        }
Rishi Gautam
  • 1,948
  • 3
  • 21
  • 31
2

Catch SocketTimeoutException and ConnectTimeoutException .

catch (SocketTimeoutException e) 
{
     e.printStackTrace();
}
catch (ConnectTimeoutException e)
{
     e.printStackTrace();
}
Chirag
  • 56,621
  • 29
  • 151
  • 198
  • @vivektiwari Connection time out exception occurs when web-service takes too much time to execute, so these two exception helps you to catch exception occurs error. If you want to test this call you werservice throug application and then immediately terminate your internet connection. – Chirag Mar 26 '13 at 06:45
  • ok.currently my server is not online. so for this situation how can i manage time duration. currently my loader visible around something 2 -3 mint. i want that will be visible only for 3 or 5 second if my server in offline. – vivek tiwari Mar 26 '13 at 06:49
  • @vivektiwari have you checked after adding above exceptions ? Because you set it to 3 - 5 seconds. – Chirag Mar 26 '13 at 06:51
  • Please log some value into exception . I want to see which exception called. – Chirag Mar 26 '13 at 06:56
  • i just posted my log. but it will never give any error or post any value before 2 3 mint. – vivek tiwari Mar 26 '13 at 07:11
  • i think this exception is not called. – vivek tiwari Mar 26 '13 at 07:12
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/26914/discussion-between-vivek-tiwari-and-chirag-raval) – vivek tiwari Mar 26 '13 at 07:17