[ Back | Previous | Next ]

Using (Http)URLConnection.setRequestProperty

Package:
java.net.*
Product:
JDK
Release:
1.1
Related Links:
General
URLConnection
URLDecoder
Comment:

Here are some samples:

  1. sending binary data
  2. sending user agent
  3. sending authentication

#1 urlConn.setRequestProperty("CONTENT-TYPE", "application/x-www-form-urlencoded"); System.out.println("Content type = " + urlConn.getRequestProperty("CONTENT- TYPE")); // returns "application/x-www-form-urlencoded" out = new PrintStream(urlConn.getOutputStream()); out.print(strPostInfo); // this does not work; content-type is blank #2 ... connection = url.openConnection(); connection.setRequestProperty ( "User-agent", "my agent name"); connection.setRequestProperty ( "From", "my name"); stream = connection.getInputStream(); ... This compiles and runs fine except the request has been sent before I get a chance to set the request headers! The server side gets "Java1.02" as the user-agent. I've also tried: ... import sun.net.www.protocol.http.HttpURLConnection; ... conn = new HttpURLConnection(url); conn.setRequestProperty ( "User-agent", "my agent name"); conn.setRequestProperty ( "From", "my name"); conn.connect(); stream = conn.getInputStream(); ... #3 import java.net.*; import java.io.*; import sun.misc.*; public class Geturl { public static void main (String url) { System.out.println(Geturl(url, "", "")); } public static String encode (String source) { BASE64Encoder enc = new sun.misc.BASE64Encoder(); return(enc.encode(source.getBytes())); } public static String Geturl (String URL, String Name, String Password) { String thisLine; String retVal; URL u; URLConnection uc; retVal = ""; try { u = new URL(URL); try { uc = u.openConnection(); if (Name != null) { uc.setRequestProperty("Authorization", "Basic " + encode(Name + ":" + Password)); } InputStream content = (InputStream)uc.getInputStream(); BufferedReader in = new BufferedReader (new InputStreamReader (content)); String line; while ((line = in.readLine()) != null) { retVal += line; } } catch (Exception e) { return ""; } } catch (MalformedURLException e) { return(URL + " is not a parseable URL"); } return retVal; } }

1