2014-09-10 28 views
-1

我正在使用RestTemplate執行URL,然後打印出它的http狀態碼。如何有效地獲得每個http狀態碼的計數?

ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); 
System.out.println(response.getStatusCode()); 

現在我需要做的是,我需要獲得每個狀態碼的計數並將其作爲鍵和值存儲在地圖中。意思是每個狀態碼到達多少次。如果http 200狀態碼達到100次左右,那麼我希望看到它的數量。

我可以通過爲每個狀態碼設置多個臨時變量並相應增加計數來實現。但除此之外還有其他簡單的方法可以做到嗎?

回答

1

使用Map也許? 以狀態爲關鍵字,值爲計數器。

Map<String,Integer> counters = new HashMap<>(); 
... 
synchronized (counters) { 

    String code = response.getStatusCode(); 
    Integer counter = counters.get(code); 

    if (counter == null) { 
    counters.put(code, 1); 
    } else { 
    counters.put(code, counter + 1) 
    } 
} 
+0

這就是我在我的問題中提到的。我可以有幾個臨時變量,具體取決於有多少Http狀態碼,然後繼續相應地增加計數。但是有沒有其他簡單的方法。這就是我的問題。 – john 2014-09-10 21:58:20

+0

與'Map',你將只有一個「temp」變量。我不認爲會比這更簡單。我會盡量用一個小例子來更新我的答案。 – 2014-09-10 22:02:09

0
Map<Integer,Integer> statusMap = new HashMap<Integer,Integer>(); 

public void store(int code) 
{ 
    if (statusMap.containsKey(code)) 
    { 
     int value = statusMap.get(code); 
     statusMap.put(code,value+1); 
    } 
    else 
    { 
     statusMap.put(code,1);  
    } 
} 

public void list() 
{ 
    Iterator<Integer> iter = statusMap.keySet().iterator(); 
    while(iter.hasNext()) 
    { 
     int code = iter.next(); 
     System.out.println(code + " : " + statusMap.get(code)); 
    } 
} 
0

使用HashMap,則:

  • 如果您httpcode是不是已經在地圖上,用數= 1
  • 插入如果你的httpcode中已經存在地圖,然後增加其計數器

    HashMap<Integer, Integer> mapCount = new HashMap<Integer, Integer>(); 
    
    // ... 
    
    void updateMap(Integer httpCode) { 
        if (!mapCount.containsKey(httpCode)) { 
         mapCount.put(httpCode, 1); 
        } else { 
         // update counter 
         int counter = mapCount.get(str).intValue() + 1; 
         // overwrite existing with update counter 
         mapCount.put(httpCode, counter + 1); 
        } 
    } 
    
    // ... 
    
0

由於您實際上是在尋求其他方法,因此可以使用int數組的索引來表示接收到的HTTP代碼。

喜歡的東西:

// initialization 
int[] responses = new int[600]; 

// for each received response 
responses[response.getStatusCode().value()]++ 

// retrieving the number of HTTP 200 received 
System.out.println("Number of HTTP 200 received : " + responses[HttpStatus.OK.value()] /* or simply responses[200] */); 

不知道什麼能帶給雖然表:即使是快一點,有很多確實是數組,最終會浪費在整數的。其他答案詳細介紹了Map的方法,這是更好的imho,因爲更明確地說明你正在嘗試做什麼(即計算特定HTTP狀態碼的出現次數)。當編寫代碼時,清晰度是關鍵:)