Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected response code for CONNECT: 400

Some of my users are getting this exception a lot when they are trying to connect.

java.io.IOException: Unexpected response code for CONNECT: 400
    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeTunnel(HttpsURLConnectionImpl.java:509)
    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:463)
    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:442)
    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
    at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)

400 means bad request but the same request succeeds after a few seconds. I double checked the request and there is nothing wrong with it. I checked with the server logs as well and it appears the request has not even reached our server.

I'm using a simple HttpUrlConnection to connect.

URL connectURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setReadTimeout(30000); 
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept-Encoding", "deflate, gzip");
connection.setRequestProperty("Content-Length", postParameters.length() + "");

conn.connect();

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(mRequestObj.getPostParameters());
writer.flush();
writer.close();

responseCode = conn.getResponseCode();

BufferedInputStream bis = null;
try {
    bis = new BufferedInputStream(conn.getInputStream());
}
catch(IOException io) {
    if(conn.getErrorStream() != null) 
        bis = new BufferedInputStream(conn.getErrorStream());
    else 
        throw io;
}

... 

Anybody else faced this issue? Anything at all that could help?

like image 518
Sudarshan Bhat Avatar asked Nov 08 '13 11:11

Sudarshan Bhat


1 Answers

It's an old question but maybe someone will find it helpful.

An exception was thrown because of the proxy tunneling which failed for some reason. That's why your web server shown nothing, it was not reached at all.


The following description refers to CONNECT method type:

This specification reserves the method name CONNECT for use with a proxy that can dynamically switch to being a tunnel

It was copied from HTTP specification.


Unfortunately, you can't do much about it unless you have a control over the proxy server. What you can do is catch an exception and retry connection.

like image 115
Damian Petla Avatar answered Oct 24 '22 07:10

Damian Petla