Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

URLConnection to servlet

 
arnold yan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm writing a java client that communicates with a servlet. But my client does not seem to hit the servlet, yet I can hit the servlet directly from a browser. Can anyone see what is wrong in my program?

Servlet
--------------------------------------------------
package cswebapp;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class Agent extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";

//Initialize global variables
public void init() throws ServletException {
}

//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
BufferedReader is = new BufferedReader( new InputStreamReader( request.getInputStream() ));
String line = is.readLine();
while (line != null) {
System.out.println(line);
line = is.readLine();
}
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Agent</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>The servlet has received a " + request.getMethod() +
". This is the reply.</p>");
out.println("</body>");
out.println("</html>");
out.close();
}

//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}

//Clean up resources
public void destroy() {
}
}
-----------------

client
-------------------------------------------------
package client;

import java.net.*;
import java.io.PrintWriter;
import java.io.ObjectOutputStream;


public class UrlClient {
public UrlClient() {
}

public static void main(String[] args) {
String urlString = "http://localhost:7001/CS/agent";
try {
URL url = new URL(urlString);
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
urlConn.setDefaultUseCaches(false);
urlConn.setRequestProperty ("Content-Type", "text/html");

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

pWriter.println("test string");

pWriter.flush();
pWriter.close();

} catch (Exception e) {

}
}
}
----------------------------------

Thanks a lot!
 
Pavel Cherkashin
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See example in my posting
here
This works fine.
But tell me
1. whether your client will go through the proxy

Your client code looks bad, because it does not read
responce. It may cause the problem.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic