Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection sends a POST request even though httpCon.setRequestMethod("GET"); is set

Here is my code:

String addr = "http://172.26.41.18:8080/domain/list";  URL url = new URL(addr); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setDoInput(true); httpCon.setUseCaches(false); httpCon.setAllowUserInteraction(false); httpCon.setRequestMethod("GET"); httpCon.addRequestProperty("Authorization", "Basic YWRtaW4fYFgjkl5463");  httpCon.connect();  OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());  System.out.println(httpCon.getResponseCode()); System.out.println(httpCon.getResponseMessage());  out.close(); 

What I see in response:

500 Server error

I open my httpCon var, and what I see:

POST /rest/platform/domain/list HTTP/1.1

Why is it set to POST even though I have used httpCon.setRequestMethod("GET"); to set it to GET?

like image 903
Lesya Makhova Avatar asked Jan 06 '12 15:01

Lesya Makhova


People also ask

What is the use of HttpURLConnection in Java?

HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol.

What is setRequestMethod head?

setRequestMethod( "HEAD" ); When processing a HEAD request, the server returns a response without the body content. Only the header fields are returned.


1 Answers

The httpCon.setDoOutput(true); implicitly set the request method to POST because that's the default method whenever you want to send a request body.

If you want to use GET, remove that line and remove the OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream()); line. You don't need to send a request body for GET requests.

The following should do for a simple GET request:

String addr = "http://172.26.41.18:8080/domain/list"; URL url = new URL(addr); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setUseCaches(false); httpCon.setAllowUserInteraction(false); httpCon.addRequestProperty("Authorization", "Basic YWRtaW4fYFgjkl5463"); System.out.println(httpCon.getResponseCode()); System.out.println(httpCon.getResponseMessage()); 

See also:

  • Using java.net.URLConnection to fire and handle HTTP requests

Unrelated to the concrete problem, the password part of your Authorization header value doesn't seem to be properly Base64-encoded. Perhaps it's scrambled because it was examplary, but even if it wasn't I'd fix your Base64 encoding approach.

like image 136
BalusC Avatar answered Sep 22 '22 10:09

BalusC