Search code examples
javajsonhttp-postapi-keyrequest-headers

Java/Json - How to add/pass an ApiKey in the HttpPost request header?


I don't want to pass the apiKey using request.setEntity() method. I only want to pass it in the request header. Is it correct if I name the header as "Authorization"? Please correct me if what I'm doing is wrong.

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(restAPIServiceURL);
request.addHeader("Content-Type", "application/json");
request.addHeader("Accept","application/json");
request.addHeader("Authorization","apiKey=AIzaSyCXhu........");
request.setEntity(new StringEntity(jsonString)); //I have other data to pass as Entity.

HttpResponse response = httpClient.execute(request);

Is there any other better way to pass the apiKey in the request header?


Solution

  • Yes. You can use this

    String API_KEY = "YOUR API KEY";
    String basicAuth = "Basic"  + new String(Base64.encode(API_KEY.getBytes(), Base64.DEFAULT));
    request.addHeader("Authorization", basicAuth);