我不想使用 request.setEntity() 方法传递 apiKey。我只想将其传递到请求 header 中。如果我将 header 命名为“授权”是否正确?如果我做的不对,请纠正我。
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);
还有其他更好的方法在请求 header 中传递 apiKey 吗?
最佳答案
是的。你可以使用这个
String API_KEY = "YOUR API KEY";
String basicAuth = "Basic" + new String(Base64.encode(API_KEY.getBytes(), Base64.DEFAULT));
request.addHeader("Authorization", basicAuth);
关于Java/Json - 如何在 HttpPost 请求 header 中添加/传递 ApiKey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51778462/