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
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
.
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;
}
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();
InputStream inputStream;
int status = urlConnection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
inputStream = urlConnection.getErrorStream();
}
else {
inputStream = urlConnection.getInputStream();
}