使用 Java UrlConnection 发送 HTTP 标头信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3199231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:46:25  来源:igfitidea点击:

Sending HTTP Header Info with Java UrlConnection

java

提问by Chiggins

Alright, so I have this bit of code, and when I make the request, I would like to include some HTTP Header info. How would I go about doing that?

好的,所以我有这段代码,当我发出请求时,我想包含一些 HTTP 标头信息。我该怎么做呢?

public boolean call(String apiCall) {
    if (this.apiCalls.containsKey(apiCall)) {
        try{
            URL url = this.apiCalls.get(apiCall);
            url = new URL(url.toString() + "?memberid=76710");

            URLConnection urlConn = url.openConnection();

            InputStream is = urlConn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while((current = bis.read()) != -1){
                baf.append((byte)current);
            }

            this.responseResultText = new String(baf.toByteArray());
            return true;
        } catch(Exception e){
            this.responseResultText = e.getMessage();
            return false;
        }
    }
    this.responseResultText = "API call " + apiCall + " doesn't exist.";
    return false;
}

Thanks!

谢谢!

回答by BalusC

Use URLConnection#setRequestProperty().

使用URLConnection#setRequestProperty().

connection.setRequestProperty("Content-Type", "text/plain");

See also:

也可以看看: