how to set Http connection timeout on Android

后端 未结 2 1192
再見小時候
再見小時候 2020-12-21 15:18

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 h

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-21 16:07

    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();
            }
    

提交回复
热议问题