2012-01-31 5 views
1

다음 코드가 있습니다. HTTP 응답 코드 -1이 표시됩니다. 문제를 해결하기 위해 http 응답 코드를 확인하기 전에 잠시 접속을 기다려야하는지 알고 싶습니다.Android HttpUrlConnection 응답 대기 시간

String requestURL = "https://www.google.com"; 

HttpURLConnection connection = new HttpURLConnection; 
connection = (HttpURLConnection) requestUrl.openConnection(); 
connection.setConnectTimeout(20000); 
connection.setReadTimeout(20000); 
connection.setRequestMethod("POST"); 
connection.setDoOutput(true); 
connection.setDoInput(true); 
connection.connect(); 

OutputStreamWriter writer = new OutputStreamWriter(this.connection.getOutputStream()); 
     writer.write(getHttpData()); 
writer.flush(); 
writer.close(); 

if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
    BufferedReader reader = new BufferedReader(new inputStreamReader(connection.getInputStream())); 
} 

는 getResponseCode() 또는는 getInputStream() 차단 호출을 있습니까? 응답을 너무 빨리 읽나요? 기다려야 하나?

도움 주셔서 감사합니다. 당신이 -1의 이상한 HTTP 응답 코드를 받고있을 수

답변

3

이유 중 하나는 연결 풀링과-HTTP-연결 유지 프로 요에 (포함)까지 안드로이드 플랫폼 버전에서의 버그, 즉 안드로이드 버전 2.2입니다 .

private void disableConnectionReuseIfNecessary() { 
    // HTTP connection reuse which was buggy pre-froyo 
    if (Integer.parseInt(Build.VERSION.SDK) <= Build.VERSION_CODES.FROYO) { 
     System.setProperty("http.keepAlive", "false"); 
    } 
} 

시도를 : -

Android Developer Blog (아래 코드 조각이 적절하게 수정됩니다 우리가했던 것을 발견하지만, 그들은이 프로 요를 포함하지 않는 말을 참고) 문제를 해결하려면 다음 코드를 제공합니다 앱을 시작할 때 호출하여 문제가 해결되는지 확인하십시오.

+0

@Marek 변경 한 코드가 올바르지 않은 것 같습니다. 대답의 요점은 Roberto가'<'를'<=' –

+1

@DrewLeSueur로 바꿔야한다는 것이 었습니다. 매우 유감스럽게 생각합니다. –