dcsimg
Using GET in a HttpURLConnection
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   James_Owen
Posted On:   Monday, September 10, 2001 07:25 AM

I'm having trouble using the get method to send data to a URL. After I call setRequestMethod("GET") I call getOutputStream() which switches the request method back to post and causes the URL to return a 405 error code because the only method defined in the servlet is doGet() . Any I idea why this is happening? Thanks in advance. urlConnection = getURLConnection(url); ((HttpURLConnection) urlConnection).setInstanceFollowRedirects(false); urlConnection.setDoOutput(true); urlConnection.setAllowUserInteraction(true); ((HttpURLConnection) urlConnection).setRequestMethod("GET"); postData((String) parms.get("-D"), urlConnecti   More>>

I'm having trouble using the get method to send data to a URL.



After I call setRequestMethod("GET") I call getOutputStream() which switches the request method back to post and causes the URL to return a 405 error code because the only method defined in the servlet is doGet() . Any I idea why this is happening? Thanks in advance.



			
urlConnection = getURLConnection(url);
((HttpURLConnection) urlConnection).setInstanceFollowRedirects(false);
urlConnection.setDoOutput(true);
urlConnection.setAllowUserInteraction(true);
((HttpURLConnection) urlConnection).setRequestMethod("GET");
postData((String) parms.get("-D"), urlConnection);

			
private boolean postData(String s, URLConnection urlConnection) throws IOException {
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
urlConnection.connect();
out.print(s);
out.flush();
out.close();
((HttpURLConnection)

return true;
}

   <<Less

Re: Using GET in a HttpURLConnection

Posted By:   Christopher_Pickslay  
Posted On:   Tuesday, September 11, 2001 10:25 PM

The code for getOutputStream() in sun.net.www.protocol.http.HttpURLConnection includes the following line:


if (method.equals("GET")) this.setRequestMethod("POST");


In fact, if you use anything but POST or PUT (or GET, which is converted to POST for you), it will throw a ProtocolException with the message "HTTP method " + method + " doesn't support output".

The reason for this is that PUT and POST are the only HTTP request methods that can include a body. With other methods, the server might puke, but more likely would just ignore the body and read only the headers.

This begs the question, "why are you trying to add post data to a GET request?" Why not just implement doPost() and POST your request?

About | Sitemap | Contact