Monday, July 4, 2011

Using HttpURLConnection to send request data to servlet server

An code snippet for writing request data from servlet server:
-------------------------------------------------------------------------------------------
URL news = new URL("your URL");
news = new URL("http://140.114.85.85:8080/GetXMLFile/GetXML?key1="+IdList);
String sendIdList = URLEncoder.encode(IdList);
 //for sending data to servlet
 HttpURLConnection connection = (HttpURLConnection) news.openConnection();
  // just want to do an HTTP GET here
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("key1",sendIdList);
// give it 15 seconds to respond
connection.setReadTimeout(15*1000);
connection.connect();    
            
-------------------------------------------------------------------------------------------

Then, to receive the response data from servlet server:
-------------------------------------------------------------------------------------------

//for reading the data response
BufferedReader in = new BufferedReader(new InputStreamReader(news.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
    {
       response.getWriter().write(inputLine);
    }
in.close();
isDone = true; 

-------------------------------------------------------------------------------------------

on the servlet server side, using the request.getParameter("key") inside the methed doPost.