Java apache.HttpClient Keep-alive

时间:2016-06-01 03:40:19

标签: java apache rest

我花了最后几个小时试图解决这个问题。我已经没有想要寻求帮助的想法了。

我正在使用带有apache httpclient的REST API。 api有2个连接/秒限制和15个请求/秒。

有谁知道更好的方法将请求限制在某个数字或知道我做错了什么?任何帮助将不胜感激。

我回复的回应是:

 HTTP/1.1 200 OK
ETag:
"6916f565d802d2220ed6b3628d142225db985cc0"
Date:
Wed, 01 Jun 2016 02:34:01 GMT
Content-Length:
264
Expires:
Thu, 02 Jun 2016 02:34:01 GMT
Connection:
keep-alive
Content-Type:
application/json
Server:
openresty/1.7.0.1

{
"instruments":  [
 {
  "instrument": "AUD_CAD",
  "displayName": "AUD/CAD",
  "pip": "0.0001",
  "maxTradeUnits": 10000000
},
 {
  "instrument": "AUD_CHF",
  "displayName": "AUD/CHF",
  "pip": "0.0001",
  "maxTradeUnits": 10000000
}
 ]
 }

它有连接:保持活着。无论我做什么,它都会重新建立连接,即使HttpClient默认是持久的。有没有办法在不创建新连接的情况下发送请求。

我的实现如下:

// 主要

    main(String[] args){

Queline que = new Queline(1);

      String test1 = "no";
    for(int i = 0; i < 1;i++){

    while(test1 == "no"){
        String function1 = que.function1(settings); 
        if(function1 == "no"){
            System.out.println("Waiting too many requests");

        }
}

// Queline(限制类) - if / else用于限制请求,该请求由重置RequestNo的线程监控,请求发送后1秒

 public String function1(AccountSettings settings) throws IOException{


    System.out.println("RequestNo= " + queSync.REQUESTNO + " Max = " +     queSync.MAXREQUESTS );

    if(queSync.REQUESTNO <= MAXREQUESTS){
        //fire request
        String responseJSON = orHelper.getResponseJSON(path, settings);
        return "RAN";
    }
    else{
        //if null calling function must wait
        System.out.println("RequestNo= " + queSync.REQUESTNO + " Max = " + queSync.MAXREQUESTS );
        return "no";

    }

       }

// orHelper类getResponseJson函数 - 发送HttpGet

property:`HttpClient httpClient = HttpClientBuilder.create().build();`


public String getResponseJSON(String path, AccountSettings settings) throws   IOException{
String accessToken = "";
    String accountID = "";
    String accountName = "";



    if(settings != null){

        accessToken = settings.getToken();
        accountID = settings.getAccountID();
        accountName = settings.getAccountName();
   }

       HttpUriRequest httpGet = new HttpGet(path);

        httpGet.setHeader(new BasicHeader("Authorization", "Bearer " + accessToken));
        httpGet.setHeader(new BasicHeader("connection", "keep-alive" ));


        HttpResponse resp = httpClient.execute(httpGet);


    String response= parseEntityJSON(resp);
        System.out.println(response);

    return response;
    }

// parseEntityJSON在类

上面看起来像这样
      public String parseEntityJSON(HttpResponse resp) throws IOException{
    StringBuilder builder = new StringBuilder();

    BufferedReader reader = new BufferedReader(new      InputStreamReader(resp.getEntity().getContent(), "UTF-8"));

    for (String line = null; (line = reader.readLine()) != null;) {
    builder.append(line).append("\n");
     }

    return builder.toString();

     }

0 个答案:

没有答案