Send Multiple POST Requests Through a DataOutputStream in Java

 ̄綄美尐妖づ 提交于 2019-12-23 19:41:18

问题


I am trying to use a for loop to send multiple POST requests through a DataOutputStream and then close it. 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"

Example of code value: 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();

回答1:


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:

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



回答2:


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."

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. Your Java runtime is permitted to keep the actual connection open to save time and bandwidth.



来源:https://stackoverflow.com/questions/24051426/send-multiple-post-requests-through-a-dataoutputstream-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!