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

Tim*_*h93 6 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 "";
    }
Run Code Online (Sandbox Code Playgroud)

编辑:使用下面的答案更改了代码但仍然收到错误消息:它无法实例化类型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 "";
    }
Run Code Online (Sandbox Code Playgroud)

Tan*_*.7x 8

URLConnection您应该使用an HttpClient来发出请求,而不是使用a .

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

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


jua*_*ugm 6

现在不鼓励使用Apache HttpClient.您可以在此处查看:Android 6.0更改

你应该更好地使用URLConnection并强制转换为HttpURLConnection:

HttpURLConnection huc= (HttpURLConnection) url.openConnection();
huc.setRequestProperty("x-api-key","value");
Run Code Online (Sandbox Code Playgroud)