I am writing some Java code that uses Apache HttpClient
version 4.2.2
to hit a RESTful 3rd party API. This API has methods that utilize HTTP GET
, POST
, PUT
and DELETE
. It's important to note that I'm using a 4.x.x version and not 3.x.x, because the API changed a lot from 3 to 4. All relevant examples I've found have been for a 3.x.x version.
All API calls require you provide the api_key
as a parameter (regardles of which method you are using). This means that regardles of whether I'm making a GET, POST or otherwise, I need to provide this api_key
in order for the call to authenticate server-side.
// Have to figure out a way to get this into my HttpClient call,
// regardless of whether I'm using: HttpGet, HttpPost, HttpPut
// or HttpDelete...
String api_key = "blah-whatever-my-unique-api-key";
So I'm trying to figure out how to provide HttpClient
with the api_key
regardless of my request method (which in turn depends on which RESTful API method I'm trying to hit). It looks like HttpGet
doesn't even support the notion of parameters, and HttpPost
uses something called HttpParams
; but again these HttpParams
only seem to exist in 3.x.x version of HttpClient
.
So I ask: What is the proper, v4.2.2 way to attach/add my api_key
String to all four:
HttpGet
HttpPost
HttpPut
HttpDelete
Thanks in advance.
You can use URIBuilder class to build the request URI for all the HTTP methods. URI builder provides setParameter method to set the parameter.
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
The output should be
http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=