Java 如何在HTTP get请求头中设置X-Api-Key
如何使用HTTP get请求头中的apikey设置x-api-key。我试过一些东西,但似乎不起作用。 这是我的密码:Java 如何在HTTP get请求头中设置X-Api-Key,java,android,get,http-headers,Java,Android,Get,Http Headers,如何使用HTTP get请求头中的apikey设置x-api-key。我试过一些东西,但似乎不起作用。 这是我的密码: private static String download(String theUrl) { try { URL url = new URL(theUrl); URLConnection ucon = url.openConnection(); ucon.addRequ
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个方法(如下)
您应该使用
HttpClient
来发出请求,而不是使用URLConnection
一个简单的示例可能如下所示:
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(theUrl);
request.addHeader("x-api-key", apiKey);
HttpResponse response = httpclient.execute(request);
现在不鼓励使用ApacheHttpClient。您可以在这里查看: 您最好使用URLConnection并转换为HttpURLConnection:
HttpURLConnection huc= (HttpURLConnection) url.openConnection();
huc.setRequestProperty("x-api-key","value");
谢谢你的回答,但是在我把这个代码粘贴到我的代码中之后。我必须重写1个方法(连接)。我是否应该添加ucon.addRequestProperty(“x-api-key”,apiKey);在这个方法里面?还是已经很晚了,并且已经建立了连接?我已经更新了我的答案-您应该使用
HttpURLConnection
,因为URLConnection不一定使用HTTP,并且没有connect()
的实现(而HttpURLConnection
有).但是我得到一个错误,说它无法实例化HttpURLConnection(url)类型。我将更新我的帖子,上面是eclipse所说的我必须做的事情。很抱歉,我忘记了HttpURLConnection
也是抽象的。我用一个更好的解决方案更新了我的答案,该解决方案使用实际的HTTP请求,而不仅仅是URL连接。
HttpURLConnection huc= (HttpURLConnection) url.openConnection();
huc.setRequestProperty("x-api-key","value");