Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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);
–
–
–
–
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");
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.