如何在HTTP get请求的标头中设置X-Api-Key

时间:2014-10-24 16:24:56

标签: 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.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 "";
    }

2 个答案:

答案 0 :(得分:7)

您应该使用URLConnection来提出请求,而不是使用HttpClient

一个简单的例子可能如下所示:

HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(theUrl);
request.addHeader("x-api-key", apiKey);
HttpResponse response = httpclient.execute(request);

答案 1 :(得分:6)

现在不鼓励使用Apache HttpClient。您可以在此处查看:Android 6.0 Changes

你最好使用URLConnection并强制转换为HttpURLConnection:

HttpURLConnection huc= (HttpURLConnection) url.openConnection();
huc.setRequestProperty("x-api-key","value");