Thursday, June 7, 2007

Generic HTTP Invoker Using URLConnection

Using the URLConnection to invoke any HTTP services, and return the response. You can this sample to invoke services over HTTP protocol.
  • SOAP
  • JSON-RPC, or
  • Just trying to retrieve a HTML page.
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();

// Set the timeout.
urlConn.setConnectionTimeout(timeout * 1000);
urlConn.setReadTimeout(timeout * 1000);

// Specify the MIME type. 
// text/xml for SOAP
// text/plain, etc
urlConn.setRequestProperty("Content-type", contentType);
// Expected response MIME.
urlConn.setRequestProperty("Accept", contentType);

// Allow I/O for the connection.
urlConn.setDoInput(true);
urlConn.setDoOutput(true);

// Disable cache
urlConn.setUseCaches(false);

// No user interaction
urlConn.setAllowUserInteraction(false);

// To allow BASIC authentication
// create the Base 64 encoded credential.

String pwd = userId + ":" + password

sun.misc.BASE64Encoder base64Enc = new sun.misc.BASE64Encoder();
String encPwd = base64Enc.encode(pwd.getBytes());
urlConn.setRequestProperty("Authorization", "Basic" + encPwd);
urlConn.connect();

// Sending the request

PrintWriter writer = new PrintWriter(urlConn.getOutputStream());

writer.print(requestContent);

// Reading the response
StringBuffer sb = new StringBuffer();

String line;
while((line = in.readLine()) != null) {
    sb.append(line + "\n");
}

toReturn = sb.toString();

No comments: