HttpURLConnection getResponseCode没有返回

时间:2016-04-04 19:11:21

标签: android httpurlconnection

我正在尝试使用Android上的HttpURLConnection将文件发布到我们的服务器,但getResponseCode调用只是挂起而永远不会返回。问题源于文件对于服务器而言太大,因此服务器发送回错误代码413(我可以在服务器日志中看到),但在我们的设备上,似乎从未收到过。我在我们的应用程序中有以下代码:

public FileUploadUtility(URL requestURL, File uploadFile) throws IOException
{
    file = uploadFile;
    String fileName = uploadFile.getName();

    httpURLConnection = (HttpURLConnection) requestURL.openConnection();
    httpURLConnection.setUseCaches(false);
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setDoInput(true);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setRequestProperty("Content-Type", URLConnection.guessContentTypeFromName(fileName));
    //httpURLConnection.setRequestProperty("Content-Length", Long.toString(fileSize));
    long fileSize = uploadFile.length();
    httpURLConnection.setFixedLengthStreamingMode(fileSize);
    outputStream = httpURLConnection.getOutputStream();
}

/**
 * Completes the request and receives response from the server.
 *
 * @return a list of Strings as response in case the server returned
 * status OK, otherwise an exception is thrown.
 * @throws IOException
 */
public String finish(ProgressListener progressListener) throws IOException, HTTPErrorCodeException
{
    try (FileInputStream inputStream = new FileInputStream(file))
    {
        byte[] buffer = new byte[100 * 1024];
        int bytesRead;

        long fileSize = file.length();
        int total = 0;
        while ((bytesRead = inputStream.read(buffer)) != -1)
        {
            outputStream.write(buffer, 0, bytesRead);

            total += bytesRead;
            if(fileSize > 0)
            {
                progressListener.fileUploadProgress((float)total / (float)fileSize);
            }
        }
        outputStream.flush();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        throw new IOException("Error uploading file: " + e.getMessage());
    }

    String response;

    // Checks server's status code first
    int status = httpURLConnection.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK)
    {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())))
        {
            StringBuilder builder = new StringBuilder();
            String output;
            while ((output = reader.readLine()) != null)
            {
                builder.append(output);
            }
            response = builder.toString();
            Log.i("Server response body", response);
        }
        httpURLConnection.disconnect();
        httpURLConnection = null;
    }
    else
    {

        String serverResponseMessage = httpURLConnection.getResponseMessage();
        Log.i("Server Response Message", serverResponseMessage);

        try (BufferedReader responseReader = new BufferedReader(new InputStreamReader((httpURLConnection.getInputStream()))))
        {
            StringBuilder builder = new StringBuilder();
            String output;
            while ((output = responseReader.readLine()) != null)
            {
                builder.append(output);
            }
            Log.i("Server response body", builder.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        try (BufferedReader errorReader = new BufferedReader(new InputStreamReader((httpURLConnection.getErrorStream()))))
        {
            StringBuilder builder = new StringBuilder();
            String output;
            while ((output = errorReader.readLine()) != null)
            {
                builder.append(output);
            }
            Log.i("Server error", builder.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        throw new HTTPErrorCodeException(status);
    }

    return response;
}

重申一下,问题不在于'为什么服务器拒绝上传',这就是为什么HttpURLConnection似乎没有拿起响应代码。当进入调试器时,看起来HttpURLConnection试图写入输出缓冲区,但服务器已经在应用程序完成写入输出缓冲区之前发送了响应代码(因为服务器已根据标头拒绝了POST)。服务器是Nginx转发到Node.JS实例,如果这有帮助,但正如我在日志中看到413,我认为这是应用程序方面的问题。它挂在以下行:

int status = httpURLConnection.getResponseCode();

1 个答案:

答案 0 :(得分:1)

事实证明问题是HttpURLConnection想要在读取任何响应之前上传整个身体。 Nginx正在发送413响应并在应用程序发送正文之前关闭连接,但HttpURLConnection仍在尝试发送正文。由于连接在Nginx端关闭,发送数据失败,但HttpURLConnection没有指定默认超时。理想情况下,HttpURLConnection会在尝试编写输出时检查早期响应头,它可能会在以后的Android版本中执行此操作(我在4.4上进行测试,所以我不确定这在以后的版本中是否更好)。目前,设置超时似乎有效:

httpURLConnection.setConnectTimeout(10 * 1000);
httpURLConnection.setReadTimeout(10 * 1000);