即使httpCon.setRequestMethod(" GET"),HttpURLConnection也会发送POST请求;已设定 [英] HttpURLConnection sends a POST request even though httpCon.setRequestMethod("GET"); is set
问题描述
这是我的代码:
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服务器错误
500 Server error
我打开 httpCon
var,以及我看到的内容:
I open my httpCon
var, and what I see:
POST / rest / platform / domain / list HTTP / 1.1
POST /rest/platform/domain/list HTTP/1.1
为什么它设置为POST,即使我使用 httpCon.setRequestMethod(GET);
来设置它GET?
Why is it set to POST even though I have used httpCon.setRequestMethod("GET");
to set it to GET?
推荐答案
httpCon.setDoOutput(true);
含蓄地将请求方法设置为POST,因为只要您想发送请求正文,这就是默认方法。
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.
如果要使用GET,请删除该行并删除 OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
line。您无需为GET请求发送请求正文。
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.
以下内容适用于简单的GET请求:
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());
参见:
- 使用java.net .URLConnection以触发和处理HTTP请求
- Using java.net.URLConnection to fire and handle HTTP requests
See also:
不相关对于具体问题,授权
标头值的密码部分似乎没有正确地进行Base64编码。也许它是乱码的,因为它是示例性的,但即使它不是我修复你的Base64编码方法。
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.
这篇关于即使httpCon.setRequestMethod(" GET"),HttpURLConnection也会发送POST请求;已设定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!