404 Not Found error for companies search API

    public String doInBackground(String ... args){

        //url of api service
        String data =  "https://api.companieshouse.gov.uk/search/companies?q=Apple";
        try {
            HttpsURLConnection conn = null;
            URL url = new URL(data);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestProperty(HttpHeaders.AUTHORIZATION, mContext.getString(R.string.api_key_companies_house));
            conn.setReadTimeout(10000 /* milliseconds */ );
            conn.setConnectTimeout(15000 /* milliseconds */ );
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            //Log.i("responseCode1", String.valueOf(conn.getResponseCode()));
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            Log.i("responseCode2", String.valueOf(conn.getResponseCode()));
            wr.flush();
            wr.close();
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            // Read Server Response
            while((line = reader.readLine()) != null) {
                sb.append(line);
                break;
            }
            reader.close();
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch(MalformedURLException e){
            e.printStackTrace();
        }catch (ProtocolException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }

        return data;
    }

I get a 404 Not Found when trying to get a response for the API. The API key is being authorised, because it didn’t give me 401 error.
Any help would be appreciated. Thanks.

Looking back - and this may no longer be the case or not apply to your code - someone did report getting a 404 from a search endpoint when they had provided an incorrectly formatted API key (e.g. they were missing the final ‘:’):

Caveat - I’m not a java coder but if this is the case then the line:

conn.setRequestProperty(HttpHeaders.AUTHORIZATION, mContext.getString(R.string.api_key_companies_house));

…will need tweaking.
Oracle’s java documentation for URLConnection combined with CH’s explanation of http basic authorization suggests that the second parameter would need to evaluate to something like “Basic YOUR_API_KEY:” - don’t know if that’s the case here?

Your query seems OK. Running this (curl) brings back search results:

curl -uYOUR_API_KEY_HERE: “https://api.companieshouse.gov.uk/search/companies?q=Apple

{
    "kind": "search#companies",
    "start_index": 0,
    "page_number": 1,
    "total_results": 4202,
    "items_per_page": 20,
    "items": 
    [
        {
            "address_snippet": "85  Great Portland Street, London, England, W1W 7LT",
    ...

I found it helpful to work things through like this e.g. checking raw http data in and out of the API. Curl is handy as you can create very simple one-line checks (free from other code complications) and examine traffic (e.g. the -I flag to show headers etc.) There are a multitude of other such tools appropriate to different environments though.

I don’t think it is to do with the API key. I just put in a colon and tried with “Basic” as you suggested and it’s gives 401 Not Authorised this time. I think the Authorisation is already correct, it’s either something that i’m missing or the server doesn/t like hence why i’m getting 404

Ah, sorry, forgot in the last post:

If you’re rolling your own http basic authentication header (as you are) you need to output the header line:

Authorization: Basic {username and password string}

Where {username and password string} is the base64 encoded username + : + password.

…and the username here is your API key, the password the empty string, so you need base64 ( YOUR_API_KEY: ) ([docs for java function][1]).

(I just learned that the character encoding here should be utf-8 although I imagine it’s always single-byte characters anyway).

See e.g. [documentation at Mozilla][2] (save reading original spec)

CH note this but don’t emphasize the details. Arguably given the volume of queries on the subject there’s a case for some more info / examples / common problems to be noted in [their documentation][3].

Anyway apologies for forgetting this in last post, been a while since I thought about this. Again - caveat - I haven’t tested this in java / with classes you’re using.

Hope this helps. Do post when you’ve sorted this so others can benefit!

Chris
[1]: Base64.Encoder (Java Platform SE 8 )
[2]: HTTP authentication - HTTP | MDN
[3]: https://developer.companieshouse.gov.uk/api/docs/index/gettingStarted/apikey_authorisation.html