This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Servlets and the fly likes Accessing servlets using URLConnection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Accessing servlets using URLConnection" Watch "Accessing servlets using URLConnection" New topic

Accessing servlets using URLConnection

Poornachandran R
Ranch Hand

Joined: Sep 11, 2002
Posts: 47
Hai all,
Good morning.
I have a small problem in accessing servlets using URLConnection in stand-alone application. Following is the snippet of client and servlet.
URL url = new URL("http://mymachine/abc/Servlet");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("Content-type", "application/octet-stream");
PrintWriter out = new PrintWriter(httpConnection.getOutputStream());
String str = "Hello world";


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("in doGet");
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("in doPost");
But it does not seem to invoke any of these methods in servlet.
FYI : I have deployed this servlet in Weblogic 6.1.

Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
hi Poornachandran,
u can try this after ur PrintWriter out = new PrintWriter(httpConnection.getOutputStream()); line,
BufferedInputStream bis = new BufferedInputStream(httpConnection.getInputStream());
that should work. i face the similar problem and the above solution did work.
i deduced that ONLY IF WE OPEN AN INPUT STREAM CONNECTION to the servlet, the servlet RESPONDS...DOESN'T matter if we don't want to do anything with the input stream we get (thats why we are closing it in above code).
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
I'm not sure if this is related to your problem, but you should never close the output stream until you are through with the connection - it closes the socket and you will never get any response. Instead you should flush() the output stream so the buffered data will all be sent.
I agree. Here's the link:
subject: Accessing servlets using URLConnection
It's not a secret anymore!