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(예: DefaultHtpClient 또는 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);
젤리빈에서 이것을 성공적으로 사용했지만, 오래된 플랫폼에서도 사용할 수 있을 겁니다.
HTH
자카르타의 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;
}
}
옵션은 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을 참조하십시오.
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();
만약 당신이 사용한다면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
'IT이야기' 카테고리의 다른 글
특정 그리드 크기에 대한 클래스 추가 설정 (0) | 2022.05.24 |
---|---|
vue.js 쿼리 위치 변경 탐색복제 (0) | 2022.05.24 |
Vuex에서 모든 개체 하위 속성 보기 (0) | 2022.05.24 |
Eclipse, 정적 가져오기를 포함하도록 가져오기 최적화 (0) | 2022.05.23 |
WebStorm에서 Vue.js 2 디버깅 (0) | 2022.05.23 |