• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using URL & URLConnection

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got some java code that will bascially send a GET to a Servlet. What would be the best way to do it?

Here is the scenario. A User will probably select some values on a form and then do a submit. My code will then take those values and send them to an external Servlet but as a GET Request. But when I do a call to the URL class should my url string include the parameters or is there a better way?
//Call the Servlet
URL url = new URL(http://myserver.com/ServletName?code=red%20blue%20green);
urlc = url.openConnection();
//Now get the response
URL url = new URL(server);
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
 
Stephen Huey
Ranch Hand
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A better way? That's the nature of a GET request.
I know that using Apache's Jakarta Commons HttpClient (search for Commons HttpClient on Google) will allow you to abstract out some of that stuff with methods like addParameter(String paramName, String paramValue).
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're on the right track for sure. With a GET the only way to send along parameters is the URL encoding you showed. Well, there might be others, but this is most likely what the web server on the other end is expecting. Here's a chunk of code I use for this kind of thing:

I'm expecting HTML here so I read lines. If you're expecting binary stuff, images or Word docs or something like that, a byte input stream would do better.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!