简体   繁体   English

通过Java中的DataOutputStream发送多个POST请求

[英]Send Multiple POST Requests Through a DataOutputStream in Java

I am trying to use a for loop to send multiple POST requests through a DataOutputStream and then close it. 我试图使用for循环通过DataOutputStream发送多个POST请求,然后关闭它。 At the moment, only the first index of the " trades " array list is sent to the website. 目前,只有“ 交易 ”数组列表的第一个索引被发送到网站。 Any other indexes are ignored and I'm assuming they are not being sent. 任何其他索引都被忽略,我假设它们没有被发送。 I wonder if I am properly flushing the stream? 我想知道我是否正好冲洗了这条小溪? Thank you!!! 谢谢!!!

Examples of trades values: "101841599", "101841801" 交易价值的例子:“101841599”,“101841801”

Example of code value: 85e4c22 代码值示例:85e4c22

Snippet of my code: 我的代码片段:

       private ArrayList<String> trades = new ArrayList<String>();
       private String code;

            String url = "http://www.dota2lounge.com/ajax/bumpTrade.php";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
            con.setRequestProperty("Cookie", cookie);
            con.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        for(int i=0; i<trades.size(); i++){
            wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes("trade=" + trades.get(i) + "&code=" + code);
            wr.flush();
            System.out.println("again");
        }   
        wr.flush();
        wr.close();

It turns out I had to actually get the response for it to properly close the connection before I started a new one. 事实证明,在开始新连接之前,我必须真正得到它的响应以正确关闭连接。 Appending these lines to the end of the for loop fixed the issue: 将这些行附加到for循环的末尾可以解决问题:

int nothing = con.getResponseCode();
String morenothing = con.getResponseMessage();

From the HttpURLConnection javadoc : "Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances." 来自HttpURLConnection javadoc :“每个HttpURLConnection实例用于发出单个请求,但与HTTP服务器的底层网络连接可以由其他实例透明地共享。”

So if you want to send multiple requests, then for each request call obj.openConnection(), set the connection settings, open the OutputStream, and write the data. 因此,如果要发送多个请求,则为每个请求调用obj.openConnection(),设置连接设置,打开OutputStream,然后写入数据。 Your Java runtime is permitted to keep the actual connection open to save time and bandwidth. 允许您的Java运行时保持实际连接打开以节省时间和带宽。

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

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