使用Java UrlConnection发送HTTP头信息

时间:2010-07-07 21:57:49

标签: java

好吧,所以我有这段代码,当我提出请求时,我想要包含一些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;
}

谢谢!

1 个答案:

答案 0 :(得分:10)

使用URLConnection#setRequestProperty()

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

另见: