简体   繁体   English

发送 Java POST 请求而不调用 getInputStream()

[英]Sending Java POST request without calling getInputStream()

I would like to send a POST request in Java.我想用 Java 发送 POST 请求。 At the moment, I do it like this:目前,我是这样做的:

URL url = new URL("myurl");
URLConnection con = url.openConnection();
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.println("key=" + URLEncoder.encode("value"));
// we have to get the input stream in order to actually send the request
con.getInputStream();  
ps.close();

I do not understand why I have to call con.getInputStream() in order to actually send the request.我不明白为什么我必须调用 con.getInputStream() 才能实际发送请求。 If I do not call it, the request is not sent.如果我不调用它,则不会发送请求。

Is there a problem using PrintStream?使用 PrintStream 有问题吗? It should not matter if I take a PrintStream, PrintWriter or something else, right?我是否使用 PrintStream、PrintWriter 或其他东西应该没有关系,对吧?

I think this is the easiest way.我认为这是最简单的方法。

con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.print("&client_id="+ 2);
ps.print("&amount="+10);
ps.flush();
ps.close();

URL represents some source. URL代表某些来源。

URLConnection represents a connection to the resource. URLConnection表示与资源的连接。

you need call connection.connect() to connect the connection 您需要调用connection.connect()来连接连接

Try to add 尝试添加

con.setDoInput (false);
before writing to the output. 在写入输出之前。

PS: and you should also call con.connect () as swanliu says. PS:您也应该像swanliu所说的那样调用con.connect()。

Update 更新资料
This is what I came up with 这就是我想出的

 private static final void sendPostRequest (final String urlAddress, String key, String value) throws Exception { URL url = new URL (urlAddress); URLConnection con = url.openConnection (); con.setDoOutput (true); con.setDoInput (false); PrintStream ps = new PrintStream (con.getOutputStream ()); ps.println (key + "=" + URLEncoder.encode (value, "UTF-8")); ps.flush (); con.connect (); ps.close (); } 

I checked with WireShark that a tcp connection is being established and that closed. 我用WireShark检查了是否建立了TCP连接,并关闭了它。 But don't know how check that the server received the request. 但是不知道如何检查服务器是否收到了请求。 If you have a quick way to check it you may try that code. 如果您有快速的方法来检查它,则可以尝试使用该代码。

I think a post of another thread answered my question. 我认为另一个主题的帖子回答了我的问题。 Sorry, but I found it too late. 对不起,但是我发现为时已晚。 You can find it here . 你可以在这里找到它。

PS: Unfortunately, Stackoverflow added my last answer to the question as a comment, because my answer was too short. PS:不幸的是,因为我的答案太短了,所以Stackoverflow在评论中添加了我最后的答案。 And it is not possible to mark a comment as the correct answer... Hope this one is long enough :-) 而且不可能将评论标记为正确答案...希望这个评论足够长:-)

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

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