HttpURLConnection java.io.FileNotFoundException

不羁岁月 提交于 2019-11-28 04:29:28
Dori

You can get a FileNotFoundException from HttpUrlConnection (and OkHttpClient) if your server returns >= HTTPStatus.BAD_REQUEST (400). You should check the status code first to check what stream you need to read.

int status = connection.getResponseCode();

if(status >= HttpStatus.SC_BAD_REQUEST)
    in = connection.getErrorStream();
else
    in = connection.getInputStream();

HttpStatus deprecated. Latest syntax seems to be:

            InputStream inputStream;

            int status = urlConnection.getResponseCode();

            if (status != HttpURLConnection.HTTP_OK)
                inputStream = urlConnection.getErrorStream();
            else
                inputStream = urlConnection.getInputStream();

Had the same problem, solved like you said:

urlConnection.setDoOutput(false);

Note that you must set it to false because it's true by default.
Note that you must set it to false because Volley HurlStack was setting it to true.
Take care ;)

EDIT: I've just checked the code and by default it's false as @Abraham Philip said. But I had to set it to false because if I called getDoOutput() it was returning true. I found that Volley HurlStack was setting it to true. So, my conclusion is, setDoOutput to false and it will work.

package java.net;
public abstract class URLConnection {
...

    /**
     * Specifies whether this {@code URLConnection} allows sending data.
     */
    protected boolean doOutput;

...
    public boolean getDoOutput() {
        return doOutput;
    }

    public void setDoOutput(boolean newValue) {
        checkNotConnected();
        this.doOutput = newValue;
    }

I faced an issue, where executing a HEAD-Request threw a FileNotFoundException.
The reason is, that a response to a HEAD does not have a body and therefore a call to getInputStream throws a FileNotFoundException.

So if you are executing a HEAD, you should not try to get the InputStream.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!