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 "";
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With