Programing

Java에서 Android에 대한 HttpResponse 시간 초과를 설정하는 방법

lottogame 2020. 3. 4. 08:06
반응형

Java에서 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);

너무 오래 기다리지 않기 위해 타임 아웃을 설정하는 방법을 아는 사람이 있습니까?

감사!


이 예에서는 두 개의 시간 초과가 설정되었습니다. 연결 시간 초과가 발생 java.net.SocketTimeoutException: Socket is not connected하고 소켓 시간이 초과되었습니다 java.net.SocketTimeoutException: The operation timed out.

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

클라이언트에서 설정을 설정하려면

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

JellyBean에서 이것을 성공적으로 사용했지만 이전 플랫폼에서도 작동해야합니다 ....

HTH


Jakarta의 http 클라이언트 라이브러리사용하는 경우 다음과 같은 작업을 수행 할 수 있습니다.

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

기본 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/


@ kuester2000의 답변이 효과가 없다고 말하는 사람들은 HTTP 요청에 먼저 DNS 요청으로 호스트 IP를 찾은 다음 서버에 대한 실제 HTTP 요청을 시도하십시오. DNS 요청 시간이 초과되었습니다.

DNS 요청 시간 초과없이 코드가 작동하면 DNS 서버에 연결하거나 Android 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());
}   

이 수업은 이 블로그 게시물에 있습니다. 당신이 그것을 사용할 경우 가서 비고를 확인하십시오.

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

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

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

옵션은 Square 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을 참조하십시오 .


를 사용하는 경우 여기에 설명 된대로 HttpURLConnection전화 하십시오 .setConnectTimeout()

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

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

참고 URL : https://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java



반응형