Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在HTTP get请求头中设置X-Api-Key_Java_Android_Get_Http Headers - Fatal编程技术网

Java 如何在HTTP get请求头中设置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

如何使用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个方法(如下)


您应该使用
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");