如何有效地获得每个http状态码的计数?

问题描述:

我正在使用RestTemplate执行URL,然后打印出它的http状态码。如何有效地获得每个http状态码的计数?

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

现在我需要做的是,我需要获得每个状态码的计数并将其作为键和值存储在地图中。意思是每个状态码到达多少次。如果http 200状态码达到100次左右,那么我希望看到它的数量。

我可以通过为每个状态码设置多个临时变量并相应增加计数来实现。但除此之外还有其他简单的方法可以做到吗?

使用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

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)); 
    } 
} 

使用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); 
        } 
    } 
    
    // ... 
    

由于您实际上是在寻求其他方法,因此可以使用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状态码的出现次数)。当编写代码时,清晰度是关键:)