【问题标题】:Sending Java POST request without calling getInputStream()发送 Java POST 请求而不调用 getInputStream()
【发布时间】:2011-11-20 20:46:05
【问题描述】:

我想用 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 或其他东西应该没关系,对吧?

【问题讨论】:

  • 尝试用ps.flush()替换那个电话。
  • 我已经尝试过了,但没有帮助。 ps.println() 的每次调用都已经调用了 flush()...
  • 对不起,现在我找到了问题的答案:stackoverflow.com/questions/4844535/…

标签: java post io


【解决方案1】:

URL 代表一些来源。

URLConnection 表示与资源的连接。

你需要调用connection.connect()来连接

【讨论】:

    【解决方案2】:

    尝试添加

    con.setDoInput (false);
    在写入输出之前。

    P.S.:你也应该像 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 连接正在建立并关闭。但不知道如何检查服务器是否收到了请求。 如果您有快速检查的方法,可以尝试该代码。

    【讨论】:

      【解决方案3】:

      我认为另一个帖子的帖子回答了我的问题。对不起,但我发现它太晚了。你可以找到它here

      PS:不幸的是,Stackoverflow 将我对该问题的最后一个答案添加为评论,因为我的答案太短了。而且不可能将评论标记为正确答案...希望这个足够长:-)

      【讨论】:

        【解决方案4】:

        我认为这是最简单的方法。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-16
          • 2018-10-29
          • 1970-01-01
          • 2011-01-12
          • 1970-01-01
          • 2015-08-06
          • 2020-12-29
          • 1970-01-01
          相关资源
          最近更新 更多