2009-03-29 14 views
315

मैं कनेक्शन स्थिति की जाँच के लिए निम्नलिखित समारोह बनाया है:जावा में Android के लिए HttpResponse समाप्ति सेट कैसे

private void checkConnectionStatus() { 
    HttpClient httpClient = new DefaultHttpClient(); 

    try { 
     String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/" 
        + strSessionString + "/ConnectionStatus"; 
     Log.d("phobos", "performing get " + url); 
     HttpGet method = new HttpGet(new URI(url)); 
     HttpResponse response = httpClient.execute(method); 

     if (response != null) { 
     String result = getResponse(response.getEntity()); 
     ... 

जब मैं निष्पादन के परीक्षण के लिए सर्वर को शट डाउन लाइन पर एक लंबे समय के इंतजार कर रहा है

HttpResponse response = httpClient.execute(method); 

क्या किसी को भी लंबे समय तक प्रतीक्षा से बचने के लिए टाइमआउट सेट करने का तरीका पता है?

धन्यवाद!

उत्तर

614

मेरे उदाहरण में दो समय समाप्ति सेट कर रहे हैं। कनेक्शन टाइमआउट फेंकता है "java.net.SocketTimeoutException: सॉकेट कनेक्ट नहीं है" और सॉकेट टाइमआउट "java.net.SocketTimeoutException: ऑपरेशन का समय समाप्त हो गया"।

HttpGet httpGet = new HttpGet(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); 
HttpResponse response = httpClient.execute(httpGet); 

आप किसी भी मौजूदा httpclient (जैसे DefaultHttpClient या AndroidHttpClient) के पैरामीटर सेट करने के लिए समारोह setParams() का उपयोग कर सकते हैं।

httpClient.setParams(httpParameters); 
+0

क्या होगा यदि आप 'AndroidHttpClient' का उपयोग कर रहे हैं? आप पैरामीटर कैसे संलग्न करेंगे? –

+1

@ थॉमस: मैंने आपके उत्तर को आपके उपयोगकेस – kuester2000

+3

के समाधान के साथ संपादित किया है यदि कनेक्शन समय समाप्त होने पर HttpResponse वापस क्या होगा? एक बार मेरा HTTP अनुरोध करने के बाद, मैं कॉल रिटर्निंग पर स्टेटस कोड की जांच करता हूं, हालांकि कॉल को समय समाप्त होने पर इस कोड को चेक करते समय मुझे NullPointerException मिलता है ... मूल रूप से, कॉल करते समय मैं स्थिति को कैसे संभाला टाइमआउट करता है? (मैं आपके उत्तर में बहुत ही समान कोड का उपयोग कर रहा हूं) – Tim

9

अपने जकार्ता के http client library का उपयोग कर रहे हैं तो आप की तरह कुछ कर सकते हैं:

 HttpClient client = new HttpClient(); 
     client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(5000)); 
     client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(5000)); 
     GetMethod method = new GetMethod("http://www.yoururl.com"); 
     method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(5000)); 
     method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
     int statuscode = client.executeMethod(method); 
+4

HttpClientParams.CONNECTION_MANAGER_TIMEOUT * _TIMEOUT पैरामीटर – Tawani

+0

आप client.getParams() का उपयोग करना चाहिए अज्ञात है। SetIntParameter (..)? डिवाइस वाईफ़ाई से जुड़ा हुआ है लेकिन वास्तव में वाईफाई के माध्यम से सक्रिय डेटा नहीं है। – adnans

+0

कैसे को खोजने के लिए –

14

क्लाइंट पर सेटिंग्स निर्धारित करने के लिए:

AndroidHttpClient client = AndroidHttpClient.newInstance("Awesome User Agent V/1.0"); 
HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000); 
HttpConnectionParams.setSoTimeout(client.getParams(), 5000); 

मैं सफलतापूर्वक JellyBean पर इस का उपयोग किया है, लेकिन यह भी पुराने प्लेटफार्मों के लिए काम करना चाहिए ....

HTH

2
HttpParams httpParameters = new BasicHttpParams(); 
      HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); 
      HttpProtocolParams.setContentCharset(httpParameters, 
        HTTP.DEFAULT_CONTENT_CHARSET); 
      HttpProtocolParams.setUseExpectContinue(httpParameters, true); 

      // Set the timeout in milliseconds until a connection is 
      // established. 
      // The default value is zero, that means the timeout is not used. 
      int timeoutConnection = 35 * 1000; 
      HttpConnectionParams.setConnectionTimeout(httpParameters, 
        timeoutConnection); 
      // Set the default socket timeout (SO_TIMEOUT) 
      // in milliseconds which is the timeout for waiting for data. 
      int timeoutSocket = 30 * 1000; 
      HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
1

यदि आप HttpURLConnection का उपयोग कर रहे हैं, तो पर कॉल करें जैसा किबताया गया है 10:

URL url = new URL(myurl); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.setConnectTimeout(CONNECT_TIMEOUT); 
1

आप httpclient-android-4.3.5 के साथ जिस तरह से उदाहरण HttpClient मूल्य बना सकते हैं, यह अच्छी तरह से काम कर सकते हैं।

SSLContext sslContext = SSLContexts.createSystemDefault(); 
     SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
       sslContext, 
       SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); 
       RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCircularRedirectsAllowed(false).setConnectionRequestTimeout(30*1000).setConnectTimeout(30 * 1000).setMaxRedirects(10).setSocketTimeout(60 * 1000); 
     CloseableHttpClient hc = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfigBuilder.build()).build(); 
6

आप डिफ़ॉल्ट http ग्राहक का उपयोग कर रहे हैं, तो यहां डिफ़ॉल्ट http पैरामीटर का उपयोग कर इसे करना है:

HttpClient client = new DefaultHttpClient(); 
HttpParams params = client.getParams(); 
HttpConnectionParams.setConnectionTimeout(params, 3000); 
HttpConnectionParams.setSoTimeout(params, 3000); 

मूल क्रेडिट http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/

4

उन लोगों के लिए के लिए चला जाता कह रही है कि इस सवाल का जवाब @ kuester2000 का काम नहीं करता है, कृपया ध्यान रखें कि HTTP अनुरोध, पहले DNS अनुरोध के साथ होस्ट आईपी को खोजने का प्रयास करें और फिर सर्वर पर वास्तविक HTTP अनुरोध करता है, इसलिए आपको DNS अनुरोध के लिए टाइमआउट सेट करने की भी आवश्यकता हो सकती है।

यदि आपका कोड DNS अनुरोध के लिए टाइमआउट के बिना काम करता है तो ऐसा इसलिए होता है क्योंकि आप किसी DNS सर्वर तक पहुंचने में सक्षम होते हैं या आप एंड्रॉइड DNS कैश को मार रहे हैं। जिस तरह से आप डिवाइस को पुनरारंभ करके इस कैश को साफ़ कर सकते हैं।

//Our objective 
String sURL = "http://www.google.com/"; 
int DNSTimeout = 1000; 
int HTTPTimeout = 2000; 

//Get the IP of the Host 
URL url= null; 
try { 
    url = ResolveHostIP(sURL,DNSTimeout); 
} catch (MalformedURLException e) { 
    Log.d("INFO",e.getMessage()); 
} 

if(url==null){ 
    //the DNS lookup timed out or failed. 
} 

//Build the request parameters 
HttpParams params = new BasicHttpParams(); 
HttpConnectionParams.setConnectionTimeout(params, HTTPTimeout); 
HttpConnectionParams.setSoTimeout(params, HTTPTimeout); 

DefaultHttpClient client = new DefaultHttpClient(params); 

HttpResponse httpResponse; 
String text; 
try { 
    //Execute the request (here it blocks the execution until finished or a timeout) 
    httpResponse = client.execute(new HttpGet(url.toString())); 
} catch (IOException e) { 
    //If you hit this probably the connection timed out 
    Log.d("INFO",e.getMessage()); 
} 

//If you get here everything went OK so check response code, body or whatever 

प्रयुक्त विधि:

//Run the DNS lookup manually to be able to time it out. 
public static URL ResolveHostIP (String sURL, int timeout) throws MalformedURLException { 
    URL url= new URL(sURL); 
    //Resolve the host IP on a new thread 
    DNSResolver dnsRes = new DNSResolver(url.getHost()); 
    Thread t = new Thread(dnsRes); 
    t.start(); 
    //Join the thread for some time 
    try { 
     t.join(timeout); 
    } catch (InterruptedException e) { 
     Log.d("DEBUG", "DNS lookup interrupted"); 
     return null; 
    } 

    //get the IP of the host 
    InetAddress inetAddr = dnsRes.get(); 
    if(inetAddr==null) { 
     Log.d("DEBUG", "DNS timed out."); 
     return null; 
    } 

    //rebuild the URL with the IP and return it 
    Log.d("DEBUG", "DNS solved."); 
    return new URL(url.getProtocol(),inetAddr.getHostAddress(),url.getPort(),url.getFile()); 
} 

इस वर्ग this blog post से है

इस कोड को एक कस्टम समय समाप्ति के साथ एक पुस्तिका DNS लुकअप शामिल करने के लिए मूल जवाब फैली हुई है। जाओ और अगर आप इसका इस्तेमाल करेंगे तो टिप्पणियों की जांच करें।

public static class DNSResolver implements Runnable { 
    private String domain; 
    private InetAddress inetAddr; 

    public DNSResolver(String domain) { 
     this.domain = domain; 
    } 

    public void run() { 
     try { 
      InetAddress addr = InetAddress.getByName(domain); 
      set(addr); 
     } catch (UnknownHostException e) { 
     } 
    } 

    public synchronized void set(InetAddress inetAddr) { 
     this.inetAddr = inetAddr; 
    } 
    public synchronized InetAddress get() { 
     return inetAddr; 
    } 
} 
1

एक विकल्प स्क्वायर से, OkHttp ग्राहक का उपयोग करने के लिए है।

पुस्तकालय निर्भरता

build.gradle में जोड़ें, इस लाइन में शामिल हैं:

compile 'com.squareup.okhttp:okhttp:x.x.x' 

कहाँ x.x.x वांछित पुस्तकालय संस्करण है।

ग्राहक

उदाहरण के लिए सेट करें, आप 60 सेकंड की समाप्ति सेट करने के लिए, इस तरह से करना चाहते हैं:

final OkHttpClient okHttpClient = new OkHttpClient(); 
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS); 
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS); 

ps: यदि आपका minSdkVersion से अधिक है 8, आप TimeUnit.MINUTES का उपयोग कर सकते हैं। तो, आप बस का उपयोग कर सकते हैं:

okHttpClient.setReadTimeout(1, TimeUnit.MINUTES); 
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES); 

इकाइयों के बारे में अधिक जानकारी के लिए TimeUnit देखते हैं।

+0

के लिए इंतजार करना होगा ओकेएचटीपी के वर्तमान संस्करण में, टाइमआउट को अलग-अलग सेट करने की आवश्यकता है: [https://github.com/square/okhttp/blob/master/samples/guide/ src/मुख्य/जावा/okhttp3/व्यंजनों/ConfigureTimeouts.java] (https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/ConfigureTimeouts.java) – thijsonline

0
public boolean isInternetWorking(){ 
    try { 
     int timeOut = 5000; 
     Socket socket = new Socket(); 
     SocketAddress socketAddress = new InetSocketAddress("8.8.8.8",53); 
     socket.connect(socketAddress,timeOut); 
     socket.close(); 
     return true; 
    } catch (IOException e) { 
     //silent 
    } 
    return false; 
} 
संबंधित मुद्दे