如何在HTTP get请求的标头中使用apikey设置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 "";
}
而不是使用URLConnection
,您应该使用发送HttpClient
请求。
一个简单的示例可能如下所示:
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(theUrl);
request.addHeader("x-api-key", apiKey);
HttpResponse response = httpclient.execute(request);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句