2014-08-27 92 views
0

我想我需要重写我的应用程序的一些模块,因为当呈现的实体数量增加,失败和错误。此刻,我正在使用JacksonHttpClient。除了我信任杰克逊之外,有人告诉我这个问题是第二个问题。 HttpClient可以处理大量回复吗? (FE this one,它是400行)处理巨大的JSON响应

除此之外,在我的应用我为了解析请求要走的路是这样的:

public Object handle(HttpResponse response, String rootName) { 
     try { 
      String json = EntityUtils.toString(response.getEntity()); 
      // better "new BasicResponseHandler().handleResponse(response)" ???? 
      int statusCode = response.getStatusLine().getStatusCode(); 
      if (statusCode >= 200 && statusCode < 300) { 
       return createObject(json, rootName); 
      } 
      else{ 
       return null; 
      } 
     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 

    } 

    public Object createObject (String json, String rootName) { 
     try { 
      this.root = this.mapper.readTree(json); 
      String className = Finder.findClassName(rootName); 
      Class clazz = this.getObjectClass(className); 
      return mapper.treeToValue(root.get(rootName), clazz); 
     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 
    } 

如何提高这一块的代码大量回应会更有效率吗?

提前致谢!

+1

什么是您遇到的确切错误/异常?你看过[请求/响应实体流](http://hc.apache.org/httpclient-3.x/performance.html#Request_Response_entity_streaming)吗? – kuporific 2014-08-27 15:24:21

+0

我不记得了,但是,我需要在Android中使用该流类吗? :0 – tehAnswer 2014-08-27 18:26:16

回答

2

东西没有必要创建String json,作为ObjectMapper#readTree可以接受InputStream为好。例如,这将会稍微高效:

public Object handle(HttpResponse response, String rootName) { 
    try { 
     int statusCode = response.getStatusLine().getStatusCode(); 
     if (statusCode >= 200 && statusCode < 300) { 
      return createObject(response.getEntity().getContent(), rootName); 
     } 
     else{ 
      return null; 
     } 
    } catch (Exception e) { 
     throw new RuntimeException(e); 
    } 

} 

public Object createObject (InputStream json, String rootName) { 
    try { 
     this.root = this.mapper.readTree(json); 
     String className = Finder.findClassName(rootName); 
     Class clazz = this.getObjectClass(className); 
     return mapper.treeToValue(root.get(rootName), clazz); 
    } catch (Exception e) { 
     throw new RuntimeException(e); 
    } 
} 
+0

我在尝试之前就试过了,但它给了我更多的问题。 – tehAnswer 2014-08-27 15:19:29

0

我有1000+行json响应处理没有问题,所以不应该是一个问题。至于更好的方法,谷歌GSON是惊人的,它将您的JSON映射到您的Java对象,无需任何特殊的解析代码。

0

我想你可以读取一个很好的旧的StringBuffer的数据。像

HttpEntity httpEntity = httpResponse.getEntity(); 
if (httpEntity != null) { 
    InputStream is = AndroidHttpClient.getUngzippedContent(httpEntity); 
    br = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(8192); 
    String s; 
    while ((s = br.readLine()) != null) sb.append(s); 
} 
+0

我不明白这会改变什么。 – njzk2 2014-08-27 15:23:25