0

We have the following code snippet for opening a BufferedReader from a URL string:

URL url = new URL(urlStr);
BufferedReader inStream = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

How can we set the HTTP Request Header Fields in this case?

Almost all the coding examples that I have seen do this by invoking the setRequestProperty method on the URLConnection object, which is instantiated by invoking the openConnection method on the URL object. For example:

URL urlObj = new URL(url);
URLConnection urlCon = urlObj.openConnection();
 
urlCon.setRequestProperty("User-Agent", "Java Client; Mac OS");
urlCon.setRequestProperty("Accept", "text/html");
urlCon.setRequestProperty("Accept-Language", "en-US");
urlCon.setRequestProperty("Connection", "close");
Sandeep
  • 1,101
  • 11
  • 24
  • See the answer in https://stackoverflow.com/questions/12732422/adding-header-for-httpurlconnection that uses HttpURLConnection instead of URLConnection – Emerson Pardo Jun 07 '21 at 14:21

0 Answers0