设置为true后,HttpURLConnection方法setDoOutput()始终返回false

时间:2016-03-15 08:14:49

标签: android file-upload httpurlconnection

我想发出一个“PUT”请求,要求将文件上传到服务器。 为此,我使用HttpURLConnection,但它无法正常工作。我已经给出了下面的代码

public static String sendFileToServer(String filePath, String targetUrl)
{
    URL url =  new URL(targetUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput( true );
    connection.setInstanceFollowRedirects( false );
    connection.setRequestMethod( "PUT" );
    connection.setUseCaches(false);
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Cache-Control", "no-cache");

}

这是我的代码,但我得到的连接方法是

doOutput = false 

method = {String@5347} "GET"

我试图解决但无论如何它都无法解决。请帮忙

1 个答案:

答案 0 :(得分:0)

请按照以下示例进行操作:

 private void openConnection(HttpURLConnection connection, HttpRequest request) throws IOException {
    if (request.getHttpBody() != null) {
        connection.setDoOutput(true);
    }
    connection.setRequestMethod(request.getMethod());
    Map<String, String> map = request.getHeaders();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();

        Logger.i("prepare headers with key = " + key + "  value = " + value);
        connection.setRequestProperty(entry.getKey(), entry.getValue());
    }
    connection.setReadTimeout((int) mReadTimeout);
    connection.setConnectTimeout((int) mConnectionTimeout);
    if (connection.getDoOutput()) {
        connection.connect();
    }
}

HttpRequest - 带标题的自定义包装类。