javarestposthttpurlconnectionhttp-status-code-401

JAVA: Cannot read body from a 401


I'm using java's HttpUrlConnection (using POST) to make a very simple rest client. The server accepts and replies aplication/xml. Even for error situations (status code 3xx, 4xx, 5xx) it sends xml payload - as specified by this server implementation - that I can get successfully from errorStream.

This is valid for all error situations expect when the server replies with 401. In this case only the errorStream is null and when trying to read from InputStream an exception is thrown.

I captured the request using Wireshark and the response is properly received. The problem is getting it on the java side


Solution

  • Using HTTPClient from Apache the problem was solved. For success and error the method to get the inputstrem (that has the response body) is always the same:

    httpresponse.getEntity().getContent()