当我调用rest api时,我会得到EOFException。我知道上面写着回应是无效的。但不应该。我在ios应用程序中使用相同的api没有任何问题。
这是我的代码:

try {
    url = new URL(baseUrl);
}
    // Thrown when URL could not be parsed
    catch (MalformedURLException me) {
        Log.e(TAG, "URL could not be parsed. URL : " + baseUrl, me);
    }
    try {

    //      System.setProperty("http.keepAlive", "false");

    // Set connection properties
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod(method);
    urlConnection.setConnectTimeout(TIMEOUT * 1000);
    urlConnection.setChunkedStreamingMode(0);
    urlConnection.setRequestProperty("Accept", "*/*");
    urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

    //      urlConnection.setRequestProperty("Connection", "close");

    if (method.equals("POST") || method.equals("PUT")) {
        // Set to true when posting data
        urlConnection.setDoOutput(true);

        // Write data to post to connection output stream
        OutputStream out = urlConnection.getOutputStream();
        out.write(postParameters.getBytes("UTF-8"));
        Log.d(TAG, "Data written to output stream.");
    }

    //      urlConnection.connect();

    try {
        // Get response
        in = new BufferedInputStream(urlConnection.getInputStream());
    } catch (IOException e) {
            Log.e(TAG,
                    "Exception in getting connection input stream. Input stream : "
                                + in, e);
    }

    Log.d(TAG, "content length : " + urlConnection.getContentLength());
    Log.d(TAG, "content type : " + urlConnection.getContentType());

    // Read the input stream that has response
    statusCode = urlConnection.getResponseCode();
    Log.d(TAG, "Status code : " + statusCode);

    if (statusCode >= 400) {
        Log.e(TAG, "Error stream : " + urlConnection.getErrorStream().toString());
    }
    // Passing input stream to a function.
    readStream(in, statusCode);
} catch (ProtocolException pe) {
    Log.e(TAG,
                    "Make sure HTTP method is set before connecting to URL. Line : "
                            + getLineNumber(), pe);
} catch (IllegalStateException ie) {
    Log.e(TAG,
                    "Set connection properties before connecting to URL. Line : "
                            + getLineNumber(), ie);
}
// Thrown when connecting to URL times out
catch (SocketTimeoutException se) {
    Log.e(TAG, "Timeout before connecting to URL : " + baseUrl
                    + ". Line : " + getLineNumber(), se);


} catch (IOException e) {
    Log.e(TAG, "Exception while connecting to URL : " + baseUrl, e);
} finally {
    urlConnection.disconnect();
}

我试过跟踪,但没有成功。这些是用代码注释掉的。以下内容:
1)System.setProperty("http.keepAlive", "false");
2)urlConnection.setRequestProperty("Connection", "close");
3)urlConnection.connect();
语句Log.d(TAG, "Status code : " + statusCode);未被记录。正常情况下可以。
Logcat屏幕截图:

最佳答案

显然,这是由于httpurlconnection中的一个错误造成的(请参见this answer on StackOverflow)。我建议您实现一个重试机制。这就是我所实现的,例如:

/** POST an object on the server using the REST API. */
private int httpPOST(String path, JSONObject json) {
    final static int MAX_RETRIES = 3;
    int numTries = 0;
    int responseCode = 0;
    HttpsURLConnection urlConnection = null;
    final long startTime = System.currentTimeMillis();

    while (numTries < MAX_RETRIES) {

        if (numTries != 0) {
            LOGV(TAG, "Retry n°" + numTries);
        }

        // Create (POST) object on server
        try {
            byte[] bytes = json.toString().getBytes("UTF-8");
            URL url = new URL(path);
            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setFixedLengthStreamingMode(bytes.length);
            urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            LOGV(TAG, "HTTP POST " + url.toString());
            OutputStream out = urlConnection.getOutputStream();
            out.write(bytes);
            out.close();
            responseCode = urlConnection.getResponseCode();
            LOGV(TAG, "HTTP POST response code: " + responseCode + " (" + (System.currentTimeMillis() - startTime)
                    + "ms)");
            return responseCode;

        } catch (UnsupportedEncodingException e) {
            LOGV(TAG, "Unsupported encoding exception");
        } catch (MalformedURLException e) {
            LOGV(TAG, "Malformed URL exception");
        } catch (IOException e) {
            LOGV(TAG, "IO exception: " + e.toString());
            // e.printStackTrace();
        } finally {

            if (urlConnection != null)
                urlConnection.disconnect();
        }

        numTries++;
    }

    LOGV(TAG, "Max retries reached. Giving up...");

    return responseCode;

}

关于java - 使用HttpUrlConnection获取java.io.EOFException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17208336/

10-10 23:44