URLConnection.setDoOutput(true)导致Get请求变Post请求?

前言

在写一个服务器下载图片并保存到SDcard上的基本功能的时候,部分代码自然而然地写成这样:

1
2
3
4
5
6
7
8
9
10
11
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();

String path = BeautifyUtil.getDownloadsWallpaperPath();
File file = new File(path + "/" + mWallpaperInfo.getFileName());

FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = connection.getInputStream();

当时还特地看了一下setDoOutput()方法的源码说明

1
2
3
4
5
6
7
8
9
10
11
/**
* Sets the flag indicating whether this {@code URLConnection} allows
* output. It cannot be set after the connection is established.
*
* @param newValue
* the new value for the flag to be set.
* @throws IllegalAccessError
* if this method attempts to change the value after the
* connection has been already established.
* @see #doOutput
*/

我需要将图片流写入到SDcard上,所以设置setDoOutput(true)再合理不过了。。

出现问题

然而运行却一直报java.io.FileNotFoundException这样的错误,好奇服务器怎么会返回404 Not Found呢,特定打开图片的连接,看看服务器确实有对应的图片啊,百思不得其解只能Google了,偶然撇到搜索结果有说将setDoOutput()方法的参数改为false就行了,我抱着不解的态度试试,居然真好了。

寻找原因

但是总不能到这就结束了啊,总要搞清楚为什么会这样啊,继续不懈的搜索,发现了这篇文章:Android 4.0 turns GET into POST

据说设置setDoOutput(true)之后,Android会认为这是一个POST请求,那么一旦服务器不支持POST请求,或者虽然支持,但是必须的参数你没有传过去,那么就会返回404 NOT FOUND,就有了上面的那个FileNotFound的异常了

参考