Java/Json - 如何在 HttpPost 请求中 add/pass 一个 ApiKey header?

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

我不想使用 request.setEntity() 方法传递 apiKey。我只想在请求中传递它header。如果我将 header 命名为 "Authorization" 是否正确?如果我做的不对,请纠正我。

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);

有没有其他更好的方式在请求中传递apiKeyheader?

是的。你可以使用这个

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