Java 8 HttpUrlConnection fail to parse response with http protocol 2

mameo :

We are maintaining a project which currently run on java 8. Now we have to call a partner server through their api to migrate some data into our database.

When we call their server, we got an exception:

Caused by: org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response

Response code in this case is -1.

So i try to use curl to get data from their server, i saw that their response status line is:

HTTP/2 200

While HttpURLConnection check like this:

    if (statusLine.startsWith("HTTP/1.")) {
        int codePos = statusLine.indexOf(' ');
        if (codePos > 0) {

            int phrasePos = statusLine.indexOf(' ', codePos+1);
            if (phrasePos > 0 && phrasePos < statusLine.length()) {
                responseMessage = statusLine.substring(phrasePos+1);

            // deviation from RFC 2616 - don't reject status line
            // if SP Reason-Phrase is not included.
            if (phrasePos < 0)
                phrasePos = statusLine.length();

            try {
                responseCode = Integer.parseInt
                        (statusLine.substring(codePos+1, phrasePos));
                return responseCode;
            } catch (NumberFormatException e) { }
    return -1;

Because status line here is 2, not 1., it fail to read and parse response from server.

But we can't just upgrade our Java to higher version as it will require a lot of testing to make sure nothing break, anyone know to fix this in java 8?

Brian Agnew :

Can you make use of HttpClient 5.0 ? This supports HTTP/2 on Java 7 and above (note that I'm somewhat surprised that your partner service doesn't support a downgrade to HTTP/1.x in some form?)

Guess you like