• Post Reply Bookmark Topic Watch Topic
  • New Topic

GET via URLConnection?  RSS feed

 
marc spoon
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all!
is it possible to send a GET or HEAD request via URLConnection?
(plz don�t tell me to use a socket ;-))
i tried the following code, but i don�t get any response from the Server. Can someone plz help?

URL url;
URLConnection conn;
String s = "http://blabla.com", filename = "/index.html", line;
InputStream sin;
BufferedReader fromServer;
OutputStream sout;
PrintWriter toServer;
try
{
url = new URL(s);
conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
sin = conn.getInputStream();
fromServer = new BufferedReader(new InputStreamReader(sin));
sout = conn.getOutputStream();
toServer = new PrintWriter(new OutputStreamWriter(sout));
toServer.print("HEAD " + filename + " HTTP/1.0\n\n");
toServer.flush();
while(true)
{
line = fromServer.readLine();
System.out.println(line);
}
} catch (IOException ioe) {}
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. The URLConnection encapsulates the protocol and will make the request for you. You are trying to use it as if it were a Socket so.
The javadoc for URLConnection outlines the steps taken in setting up a connection:
  • The connection object is created by invoking the openConnection method on a URL.
  • The setup parameters and general request properties are manipulated.
  • The actual connection to the remote object is made, using the connect method.
  • The remote object becomes available. The header fields and the contents of the remote object can be accessed.
  • What you want to do is manipulate the URLConnection's request parameters in the second step. To do this, first cast the connection to a HttpURLConnection. By default, a HttpURLConnection will use a GET request. If you call setDoOutput(true), it defaults to a POST request. You can invoke other methods by calling setRequestMethod(String) - supported are GET POST HEAD OPTIONS PUT DELETE and TRACE. The actual file you request is determined by the URL - I don't think you can start with a "http://blabla.com" URL and add a filename separately later as you're trying to do.
    Once you've set up the request, simply connect() and get the input and/or output streams, or call getContent() for a higher-level representation of the response (using content handlers).
    - Peter
    [This message has been edited by Peter den Haan (edited December 15, 2001).]
 
marc spoon
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
muchas gracias Peter!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!