如何在HTTP GET请求的标头中使用API密钥设置x-api-key。我已经尝试了一些东西,但似乎它不起作用。
这是我的代码:
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 "";
}
编辑: 根据下面的答案更改了代码,但仍然收到错误消息:无法实例化类型HttpURLConnection(url)。我已经进行了更改,但现在我必须覆盖3个方法(如下)
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 "";
}
HttpURLConnection
,因为 URLConnection 并不一定使用 HTTP,并且没有connect()
的实现(而HttpURLConnection
则有)。 - Bryan HerbstHttpURLConnection
也是抽象的。我更新了我的答案,提供了一个更好的解决方案,使用实际的HTTP请求而不仅仅是URL连接。 - Bryan Herbst