HttpURLConnection java.io.FileNotFoundException

前端 未结 3 1598
温柔的废话
温柔的废话 2020-12-07 22:50

The code below works great if I connect to what seems to be Apache servers, however when I try to connect to my .Net server it throws an error. I am guessing it is a header

相关标签:
3条回答
  • 2020-12-07 23:17

    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.

    0 讨论(0)
  • 2020-12-07 23:29

    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;
        }
    
    0 讨论(0)
  • 2020-12-07 23:37

    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();
    }
    
    0 讨论(0)
提交回复
热议问题