Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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();
like image 796
lsnow2017 Avatar asked Jun 11 '26 01:06

lsnow2017


2 Answers

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();
like image 190
lsnow2017 Avatar answered Jun 13 '26 01:06

lsnow2017


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.

like image 41
mikebolt Avatar answered Jun 13 '26 01:06

mikebolt