How do I set the referer for a URLConnection?
Created May 4, 2012
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(); } } }