簡體   English   中英

發送 Java POST 請求而不調用 getInputStream()

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

我想用 Java 發送 POST 請求。 目前,我是這樣做的:

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();

我不明白為什么我必須調用 con.getInputStream() 才能實際發送請求。 如果我不調用它,則不會發送請求。

使用 PrintStream 有問題嗎? 我是否使用 PrintStream、PrintWriter 或其他東西應該沒有關系,對吧?

我認為這是最簡單的方法。

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

URL代表某些來源。

URLConnection表示與資源的連接。

您需要調用connection.connect()來連接連接

嘗試添加

con.setDoInput (false);
在寫入輸出之前。

PS:您也應該像swanliu所說的那樣調用con.connect()。

更新資料
這就是我想出的

 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 (); } 

我用WireShark檢查了是否建立了TCP連接,並關閉了它。 但是不知道如何檢查服務器是否收到了請求。 如果您有快速的方法來檢查它,則可以嘗試使用該代碼。

我認為另一個主題的帖子回答了我的問題。 對不起,但是我發現為時已晚。 你可以在這里找到它。

PS:不幸的是,因為我的答案太短了,所以Stackoverflow在評論中添加了我最后的答案。 而且不可能將評論標記為正確答案...希望這個評論足夠長:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM