user1776576
user1776576

Reputation: 103

How to make quick http requests ? (Java)

I made an application that serves as an autobuyer. Making it as fast as possible is crucial to get to the item faster than anyone else. I am using an infinite loop (i.e. for(;;)) to make continuous http requests and then parsing the JSON result.

Does anyone know how to make multiple simultaneous requests ? Mine currently does about 3 requests a second. Also is java not appropriate for this sort of application ? Should I consider using another language maybe ?

Thank you very muuuch !

Edit: I use a search function like

for(;;){
search(323213, 67);
search(376753, 89);
}

public void search(int itemID, int maxPrice) {

// sets the http request with the need cookies and headers
// processes the json. If (itemId==x&&maxPrice>y) ==> call buy method

}

Upvotes: 0

Views: 5547

Answers (4)

Sonu Dhakar
Sonu Dhakar

Reputation: 151

  1. for get request String url = "http://www.google.com/search?q=developer";

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    
    // add request header
    request.addHeader("User-Agent", USER_AGENT);
    
    HttpResponse response = client.execute(request);
    
  2. String url = "https://selfsolve.apple.com/wcResults.do";

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    
    // add header
    post.setHeader("User-Agent", USER_AGENT);
    
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
    urlParameters.add(new BasicNameValuePair("cn", ""));
    urlParameters.add(new BasicNameValuePair("locale", ""));
    urlParameters.add(new BasicNameValuePair("caller", ""));
    urlParameters.add(new BasicNameValuePair("num", "12345"));
    
    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    
    HttpResponse response = client.execute(post);
    

Upvotes: 0

Andreas Wederbrand
Andreas Wederbrand

Reputation: 40061

Using a ScheduledThreadPoolExecutor you could schedule a runnable to run with a fixed rate, say every 10 seconds, without bothering about spawning the threads your self.

Upvotes: 1

Cory Gagliardi
Cory Gagliardi

Reputation: 780

Here's another post that gives a good example of how to do this with threading: How do you create an asynchronous HTTP request in JAVA?

If you are comfortable with JavaScript, Node.JS is another good choice for this. Using Node.JS removes the need to worry about threading, because the request is done asynchronously.

Upvotes: 0

Eric J.
Eric J.

Reputation: 150178

Making requests in an infinite loop will get your IP blocked by any service that actively monitors for abuse.

If you wish to send a bunch of requests in parallel for a short period of time, spin up multiple threads and have each of them submit a request.

Java is a very capable platform for multi-threading.

Upvotes: 2

Related Questions