I'm connecting to a web server from my android application via HttpsUrlConnection
or HttpUrlConnection
depending on settings. For now I didn't have any kind of problem, but yesterday I start getting http/https status
response -1
. There is no way the web server return me this even if there is some kind of error. The server which I'm connection to is designed to return errorCode
and errorString
when there is some kind of problem. Here is the code I'm using,but I don't think the problem is here.
public void UseHttpConnection(String url, String charset, String query) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url)
.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null)
try {
output.close();
} catch (IOException logOrIgnore) {
}
}
int status = ((HttpURLConnection) connection).getResponseCode();
Log.i("", "Status : " + status);
for (Entry<String, List<String>> header : connection
.getHeaderFields().entrySet()) {
Log.i("Headers",
"Headers : " + header.getKey() + "="
+ header.getValue());
}
InputStream response = new BufferedInputStream(
connection.getInputStream());
int bytesRead = -1;
byte[] buffer = new byte[30 * 1024];
while ((bytesRead = response.read(buffer)) > 0) {
byte[] buffer2 = new byte[bytesRead];
System.arraycopy(buffer, 0, buffer2, 0, bytesRead);
handleDataFromSync(buffer2);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
So my question is, what should -1
stands for. Is it response for some kind of error or something else?
HTTP response code -1, means that something went wrong with connection or response handling. The HttpURLConnection in often buggy with keeping connections alive.
If you want to turn if off, you have to set the http.keepAlive system property into false.
The way to do this programmatically is putting this at the beginning of your application: