Problem: Often sites accepts custom http headers and cookies to get data from them. In below example we are going to read data from URL by send http cookie and header.
Solution:
Solution:
package com;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* It reads data from a site by sending cookie and custom http header
* @author lucky academy
*
*/
public class URLReaderDemo {
public static void main(String[] args)throws Exception {
//URL of the site
URL site = new URL("http://www.luckyacademy.com/services/odata/Person");
//Open Connection
URLConnection uc = site.openConnection();
//Set Cookie
uc.setRequestProperty("Cookie", "JSESSIONID=F2845FC15FCF6660EB093D00DAE73BB2; rememberMe=false");
//Set custom http header
uc.setRequestProperty("tenantId","ebay");
//read data from the site
//Setting http headers after opening input stream will not have any effect
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
No comments:
Post a Comment