How do I set the referer for a URLConnection?

Tim Rohaly

Use the setRequestProperty() method of URLConnection. The following example shows how to do this properly:

import java.net.*;
import java.io.*;

public class RequestProperty {

    public static void main(String[] args) {
        try {
            URL url = new URL("http://search.ebay.com/search/search.dll?" +
                          "MfcISAPICommand=GetResult" +
                          "&ht=1&SortProperty=MetaEndSort" +
                          "&query=generation+barbie");
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("Referer", "http://www.jguru.com/");

            InputStream stream = connection.getInputStream();
            BufferedInputStream in = new BufferedInputStream(stream);
            int length = 0;
            byte[] data = new byte[1024];
            while ((length = in.read(data)) != -1) {
                System.out.write(data);
            }
            in.close();
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact