How to Set X-Api-Key in the Header of Http Get Request
How Can I Set an X-Api-Key with the Apikey in the Header of a Http Get Request. I Have Tried Something but It Seems It Doesn't Work. Here Is My Code: Private...
How can i set an x-api-key with the apikey in the header of a HTTP get request. I have tried something but it seems it doesnt work. Here is my code:
private static String download(String theUrl)
{
try {
URL url = new URL(theUrl);
URLConnection ucon = url.openConnection();
ucon.addRequestProperty("x-api-key", apiKey);
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
return new String (baf.toByteArray());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
EDIT: Changed the code with the answer below but still getting an error message: it couldn't instantiate the type HttpURLConnection(url). I have changed it but now i have to override 3 methods (below)
private static String download(String theUrl)
{
try {
URL url = new URL(theUrl);
URLConnection ucon = new HttpURLConnection(url) {
@Override
public void connect() throws IOException {
// TODO Auto-generated method stub
}
@Override
public boolean usingProxy() {
// TODO Auto-generated method stub
return false;
}
@Override
public void disconnect() {
// TODO Auto-generated method stub
}
};
ucon.addRequestProperty("x-api-key", apiKey);
ucon.connect();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
return new String (baf.toByteArray());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
2 Answers
Instead of using a URLConnection, you should be using an HttpClient to make a request.
A simple example might look like this:
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(theUrl);
request.addHeader("x-api-key", apiKey);
HttpResponse response = httpclient.execute(request);
The use of Apache HttpClient is now discouraged. You can check it here: Android 6.0 Changes
You should better use URLConnection and cast to HttpURLConnection:
HttpURLConnection huc= (HttpURLConnection) url.openConnection();
huc.setRequestProperty("x-api-key","value");