简体   繁体   English

java HttpUrlConnection POST:需要请求提交POST的响应吗?

[英]java HttpUrlConnection POST: need to ask for a response for the POST to be committed?

I'm trying to post data on a server using java HttpUrlConnection class. 我正在尝试使用java HttpUrlConnection类在服务器上发布数据。 It seems that if I somehow read the response of the server, the post works fine, but if I don't, the information is never posted. 似乎如果我以某种方式阅读服务器的响应,帖子工作正常,但如果我不这样做,信息永远不会发布。

This kind of behaviour is not mentionned in the HttpUrlConnection doc and all examples I've seen of HttUrlConnection ask for a response from the server. 在HttpUrlConnection文档中没有提到这种行为,我见过的所有HttUrlConnection示例都要求服务器做出响应。

I want to know if I made a mistake in my code or if this is a normal behaviour of HttpUrlConnection, and if it's the case, can someone with a better understanding of how this class works explain to me why it's so? 我想知道我的代码是否犯了错误,或者这是否是HttpUrlConnection的正常行为,如果是这样的话,那么能够更好地理解这个类如何工作的人会向我解释为什么会这样?

Thanks a lot! 非常感谢!

Here is the code, the commented line is the one that makes the POST either work or fail: 这是代码,注释行是使POST工作或失败的行:

URL url=new URL("myUrl");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
connection.setRequestProperty("Host", "myHost");
connection.setDoOutput(true);
os.write(staffToPost.getBytes("utf-8"));
os.flush();
os.close();
//System.out.println(connection.getResponseCode()+" "+connection.getResponseMessage());

URLCOnnection类需要完全握手才能发生POST。这意味着,一旦打开连接,就必须回读POST实际发生的响应。

You can explicitly call URLConnection.connect() or get any information about the HTTP response such as HttpURLConnection.getResponseCode etc to trigger HTTP request. 您可以显式调用URLConnection.connect()或获取有关HTTP响应的任何信息,例如HttpURLConnection.getResponseCode等,以触发HTTP请求。

You should go through this comprehensive post on How to use java.net.URLConnection to fire and handle HTTP requests for better understanding. 您应该阅读有关如何使用java.net.URLConnection来触发和处理HTTP请求以获得更好理解的综合文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM