Monday, 30 May 2011

J2EE: Open a URL connection

The code snippet below is for a Servlet which opens a URL connection to another Servlet deployed on the same application server, authenticate using "Basic Authentication" ,read the content, make some processing on data read and then write it to the response of the current Servlet. I did so because I need a wrapper around the existing Servlet to modify its generated output and didn't have the code for the original Servlet to modify or to add a filter.

Remarks:
  • Don't try to call connection.getContentType() before you authenticate using connection.setRequestProperty(); as you will HTTP error 401 (NOT AUTHENTICATED)


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

    String scheme=request.getScheme();
    String hostname=request.getServerName();
    int port=request.getServerPort();
    String target=scheme+"://"+hostname+":"+port;
    PrintWriter writer=response.getWriter();
    response.setContentType("application/xml");
    URL temp=new URL(target+"/placecntr/seedlist  /myserver?"+request.getQueryString());
    System.out.println("URL: "+temp);
 
try{
     URLConnection connection=temp.openConnection();
     String userPassword = "username" + ":" + "password";
     String encoding = new sun.misc.BASE64Encoder().encode    (userPassword.getBytes());
     connection.setRequestProperty ("Authorization", "Basic " + encoding);
     InputStream input=connection.getInputStream();
     StringBuffer stream=new StringBuffer(1000);
 
     int i=0;
     while (i!=-1){
     byte buffer[]=new byte[1000];
     i=input.read(buffer);
     if(i!=-1){
       stream.append(new String(buffer,0,i));
     }
     }
     //Do some processing on stream if required
     writer.print(stream);
     writer.flush();
     writer.close();
}catch (Exception e){
    System.err.println(target);
    System.out.println(e.getMessage());
    e.printStackTrace();
}
}

No comments:

Post a Comment