简体   繁体   中英

Sending HTTP Header Info with Java UrlConnection

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?

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!

Use URLConnection#setRequestProperty() .

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

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM