Monday, 16 September 2013

Send Cookie and custom HTTP header using java.net.URLConnection

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:

 
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();

 
}
}

1 comment:

  1. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command.
    Java Training in Chennai

    ReplyDelete