java.net.SocketTimeoutException 가져 오기 : Android에서 연결 시간이 초과되었습니다.
나는 상대적으로 안드로이드 개발에 익숙하지 않습니다. 웹 서버에 요청을 보내고 json 개체를 구문 분석하는 Android 애플리케이션을 개발 중입니다. 자주 java.net.SocketTimeoutException: Connection timed out
서버와 통신하는 동안 예외 가 발생합니다. 어떤 경우에는 문제없이 완벽하게 작동합니다. 나는이 같은 질문이 여러 번 요청되었다는 것을 알고 있습니다. 그러나 여전히 나는이 문제에 대한 만족스러운 해결책을 얻지 못했습니다. 아래에 내 logcat 및 앱-서버 통신 코드를 게시하고 있습니다.
public JSONObject RequestWithHttpUrlConn(String _url, String param){
HttpURLConnection con = null;
URL url;
String response = "";
Scanner inStream = null;
PrintWriter out = null;
try {
url = new URL(_url);
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
if(param != null){
con.setFixedLengthStreamingMode(param.getBytes().length);
}
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
out = new PrintWriter(con.getOutputStream());
if(param != null){
out.print(param);
}
out.flush();
out.close();
inStream = new Scanner(con.getInputStream());
while(inStream.hasNextLine()){
response+=(inStream.nextLine());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(con != null){
con.disconnect();
}if(inStream != null){
inStream.close();
}if(out != null){
out.flush();
out.close();
}
}
}
Logcat :
03-25 10:55:32.613: W/System.err(18868): java.net.SocketTimeoutException: Connection
timed out
03-25 10:55:32.617: W/System.err(18868):at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
03-25 10:55:32.617: W/System.err(18868):at dalvik.system.BlockGuard
$WrappedNetworkSystem.connect(BlockGuard.java:357)
03-25 10:55:32.617: W/System.err(18868):at
org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
03-25 10:55:32.617: W/System.err(18868):at
org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
03-25 10:55:32.617: W/System.err(18868):at java.net.Socket.connect(Socket.java:1002)
03-25 10:55:32.621: W/System.err(18868):at
org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>
(HttpConnection.java:75)
03-25 10:55:32.621: W/System.err(18868): at
org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>
(HttpConnection.java:48)03-25 10:55:32.624: W/System.err(18868):at
org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect
(HttpConnection.java:322)03-25 10:55:32.624: W/System.err(18868):at
org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get
(HttpConnectionPool.java:89)03-25 10:55:32.628: W/System.err(18868):at
org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpCon
nection(HttpURLConnectionImpl.java:285)
03-25 10:55:32.628: W/System.err(18868):at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConn
ection(HttpURLConnectionImpl.java:267)
03-25 10:55:32.636: W/System.err(18868):at
org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect
(HttpURLConnectionImpl.java:205)
03-25 10:55:32.636: W/System.err(18868):at
org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputS
tream(HttpURLConnectionImpl.java:614)
03-25 10:55:32.636: W/System.err(18868):at
com.myapp.core.JSONRequest.RequestWithHttpUrlConn(JSONRequest.java:63)
03-25 10:55:32.636: W/System.err(18868): at com.myapp.core.DetailPage
$AsyncRecBooks.doInBackground(AKBookDetailView.java:265)
03-25 10:55:32.640: W/System.err(18868): at com.myapp.core.DetailPage
$AsyncRecBooks.doInBackground(AKBookDetailView.java:1)
03-25 10:55:32.640: W/System.err(18868): at android.os.AsyncTask$2.call
(AsyncTask.java:185)
03-25 10:55:32.640: W/System.err(18868): at java.util.concurrent.FutureTask
$Sync.innerRun(FutureTask.java:306)
03-25 10:55:32.640: W/System.err(18868): at java.util.concurrent.FutureTask.run
(FutureTask.java:138)
03-25 10:55:32.640: W/System.err(18868): at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
03-25 10:55:32.648: W/System.err(18868): at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
03-25 10:55:32.648: W/System.err(18868): at java.lang.Thread.run(Thread.java:1019)
03-25 10:55:32.652: E/JSON Parser(18868): Error parsing data org.json.JSONException:
End of input at character 0 of
누구든지 이것에 대한 해결책을 찾기 위해 나를 도울 수 있습니까? 미리 감사드립니다 ....
I've searched all over the web and after reading lot of docs regarding connection timeout exception, the thing i understood is that, preventing SocketTimeoutException is beyond our limit...One way to effectively handle it is to define a connection timeout and later handle it by using a try catch block.... hope this will help anyone in future who are facing the same issue.
HttpUrlConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(7000); //set the timeout in milliseconds
I'm aware this question is a bit old. But since I stumbled on this while doing research, I thought a little addition might be helpful.
As stated the error cannot be solved by the client, since it is a network related issue. However, what you can do is retry connecting a few times. This may work as a workaround until the real issue is fixed.
for (int retries = 0; retries < 3; retries++) {
try {
final HttpClient client = createHttpClientWithDefaultSocketFactory(null, null);
final HttpResponse response = client.execute(get);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new IllegalStateException("GET Request on '" + get.getURI().toString() + "' resulted in " + statusCode);
} else {
return response.getEntity();
}
} catch (final java.net.SocketTimeoutException e) {
// connection timed out...let's try again
}
}
Maybe this helps someone.
If you are testing the server in localhost your Android device must be connected to the same local network. Then the Server URL used by your APP must include your computer IP Address and not the "localhost" mask.
Set This in OkHttpClient.Builder() Object
val httpClient = OkHttpClient.Builder()
httpClient.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES) // read timeout
I was facing this problem and the solution was to restart my modem (router). I could get connection for my app to internet after that.
I think the library I am using is not managing connections properly because it happeend just few times.
I got this same error as I mistakenly changed the order of the statements
OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .connectTimeout(20, TimeUnit.SECONDS).readTimeout(20,TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS) .build();
After changing the order of writeTimeout and readTimeout, the error resolved. The final code I used is given below:
OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
public JSONObject RequestWithHttpUrlConn(String _url, String param){
HttpURLConnection con = null;
URL url;
String response = "";
Scanner inStream = null;
PrintWriter out = null;
try {
url = new URL(_url);
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
if(param != null){
con.setFixedLengthStreamingMode(param.getBytes().length);
}
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
out = new PrintWriter(con.getOutputStream());
if(param != null){
out.print(param);
}
out.flush();
out.close();
inStream = new Scanner(con.getInputStream());
while(inStream.hasNextLine()){
response+=(inStream.nextLine());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(con != null){
con.disconnect();
}if(inStream != null){
inStream.close();
}if(out != null){
out.flush();
out.close();
}
}
}
'IT Share you' 카테고리의 다른 글
동시 JUnit 테스트 (0) | 2020.11.08 |
---|---|
새 DbContext ()는 언제 만들어야합니까? (0) | 2020.11.08 |
Ruby에서 동적 메서드 호출 (0) | 2020.11.08 |
C # 엔티티 프레임 워크 : 저장소 클래스 내에서 DBContext 클래스의 올바른 사용 (0) | 2020.11.08 |
탭을 사용하지 않고 jupyter 노트북에서 자동 완성을 얻는 방법은 무엇입니까? (0) | 2020.11.08 |