Вопрос

Я надеюсь, что кто-то может помочь мне с прерывистыми соединениями, которые я получаю с помощью кода с HTTPSURLConnection. Код, который я использую, ниже:

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setReadTimeout(10 * 1000); 
if conn.getResponseCode() != 200) { 
            Log.v(TAG, "error code:" + conn.getResponseCode()); 
} 

Соединение работает в первый раз каждый раз, когда я использую его, чтобы вытащить файл json. Однако, когда я снова использую соединение, чтобы отправить команду, она всегда не удается в первый раз. Затем он обычно работает, если я отправлю команду быстро (в течение 5 секунд), но не удается, если я жду некоторое время. Я не думаю, что это проблема SSL, потому что она правильно соединяет первый раз, но я мог бы неправиться здесь. Я также пробовал много разных вариантов, таких как добавление:

conn.setUseCaches(false); 
conn.setRequestProperty("Connection","Keep-Alive"); 
conn.getHostnameVerifier(); 
conn.getSSLSocketFactory(); 
conn.setDoOutput(true); 
conn.setDoInput(true); 
conn.setRequestMethod("POST"); 
conn.wait(100); 

Однако мне не повезло. Любая помощь будет очень ценится.

Это было полезно?

Решение

Пытаться System.setProperty("http.keepAlive", "false"); Прежде чем сделать

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

Другие советы

Попробуйте этот код - это работает довольно надежно для меня:

public static final String USER_AGENT = "Mozilla/5.0 (Linux; U; Android 1.1; en-us;dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2";
private DefaultHttpClient getThreadSafeHttpClient() {
    final HttpParams params = new BasicHttpParams();
    params.setParameter("http.useragent", USER_AGENT);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    final SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    registry.register(new Scheme("https", sslSocketFactory, 443));
    final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient httpclient = new DefaultHttpClient(manager, params);
    // how to handle retries
    final HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
        public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
            if (executionCount >= 5) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                // Retry if the server dropped connection on us
                return true;
            }
            if (exception instanceof SSLHandshakeException) {
                // Do not retry on SSL handshake exception
                return false;
            }
            final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            final boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }

    };
    httpclient.setHttpRequestRetryHandler(myRetryHandler);
    return httpclient;
}

Просто небольшое дополнение к ответу M6TT выше:

private static void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (!Constants.SUPPORTS_FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top