Jagjit Bains
Jagjit Bains

Reputation: 1

RESTAPI companieshouse (UK) is returning error 401

I'm using java and the following code is returning error 401

conn.egtResponseCode() returns response code 200 But url.openStream returns error 401

Using the same APIKEY in POSTMAN works

What am I doing wrong?

public static void main(String[] args) {
    try {

        URL url = new URL("https://api.company-information.service.gov.uk//company/09022905/officers?");

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        SSLContext sc = SSLContext.getInstance("TLSv1.2"); //$NON-NLS-1$
        sc.init(null, null, new java.security.SecureRandom());
        //HttpsURLConnection con = (HttpsURLConnection) httpsURL.openConnection();
        conn.setSSLSocketFactory(sc.getSocketFactory());

        String encoded = Base64.getEncoder().encodeToString(("{my api key}"+":"+"").getBytes(StandardCharsets.UTF_8)); 
        conn.setRequestProperty("Authorization", "Basic "+encoded);
        conn.setRequestProperty("Cookie","JSESSIONID=06752D78827EDCBD8ED0FDEF382F79DB");
        conn.setRequestProperty("Host","api.company-information.service.gov.uk");
        conn.connect();

        //Getting the response code
        int responsecode = conn.getResponseCode();

        if (responsecode != 200) {
            throw new RuntimeException("HttpResponseCode: " + responsecode);
        } else {

            String inline = "";
            Scanner scanner = new Scanner(url.openStream());

what am i missing?

Upvotes: 0

Views: 178

Answers (1)

Luke Woodward
Luke Woodward

Reputation: 65034

You are creating an SSL connection to the Companies House API, setting up the authentication, SSL, headers, et cetera. All that appears to be working, as you are receiving an HTTP 200 OK response code back. So far so good.

However, when you receive this successful response, you then open a whole new connection to the URL without any of the authentication or anything else set up on it, and then attempt to read the content from this new connection. Of course, this new connection doesn't have all of the authentication and so on that the Companies House API seems to need, so the Companies House API returns an HTTP 401 Unauthorized response to you.

Your HttpsURLConnection instance conn has its own method to return the stream of your (apparently successful) connection, conn.getInputStream(). Perhaps you want to use that instead of url.openStream(), which will create a whole new connection?

Try replacing the last line of your code,

Scanner scanner = new Scanner(url.openStream());

with

Scanner scanner = new Scanner(conn.getInputStream());

Upvotes: 0

Related Questions