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

前端 未结 1 1926
旧巷少年郎
旧巷少年郎 2020-12-08 10:28

Here is my code:

String addr = \"http://172.26.41.18:8080/domain/list\";

URL url = new URL(addr);
HttpURLConnection httpCon = (HttpURLConnection) url.openCo         


        
相关标签:
1条回答
  • 2020-12-08 10:59

    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.

    0 讨论(0)
提交回复
热议问题