如何快速发出http请求? (JAVA)

时间:2012-11-12 19:51:06

标签: java json performance http request

我做了一个作为autobuyer的应用程序。尽可能快地制作物品对于比其他人更快地到达物品至关重要。我使用无限循环(即for(;;))来创建连续的http请求,然后解析JSON结果。

有谁知道如何同时发出多个请求?我目前每秒做3个请求。 java也不适合这种应用吗?我应该考虑使用其他语言吗?

非常感谢你!

编辑:我使用像

这样的搜索功能
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

}

4 个答案:

答案 0 :(得分:2)

在无限循环中发出请求会被主动监控滥用的任何服务阻止您的IP。

如果您希望在短时间内并行发送大量请求,请启动多个线程并让每个请求都提交请求。

Java是一个非常强大的多线程平台。

答案 1 :(得分:1)

使用ScheduledThreadPoolExecutor你可以安排一个可运行的固定速率运行,比如说每10秒运行一次,而不必费心自己生成线程。

答案 2 :(得分:0)

这是另一篇文章,提供了如何使用线程执行此操作的一个很好的示例: How do you create an asynchronous HTTP request in JAVA?

如果您对JavaScript感到满意,那么Node.JS是另一个很好的选择。使用Node.JS无需担心线程,因为请求是异步完成的。

答案 3 :(得分:0)

  1. 获取请求字符串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);
    
相关问题