我在http请求中遇到了一些奇怪的行为。我有一些用户说这个调用永远不会返回(标记为异步调用的微调器永远不会消失)。我以前见过这种情况,但我把它归因于通过charles proxy的仿真器。直到现在我才在电话里看到它。
我不知道是什么原因造成的,所以我把它贴在这里。这是调用,使用jackson将结果反序列化为一个值对象。我看到模拟器冻结的两个点是httpclient.execute(httpget);和getobjectmapper().readvalue(jp,syncvo.class);。
在调试时,跳过有问题的语句会导致调试器永远无法获得对单步执行的控制。同时,我看到请求发出并通过charles从服务器返回。只是应用程序似乎没有得到响应,只是坐在那里。
所以,这是密码。谢谢你的帮助!

public SyncVO sync(String userId, long lastUpdate, boolean includeFetch) throws IOException {
    SyncVO result = null;

    String url = BASE_URL + "users/" + userId + "/sync" + "?" + "fetch=" + includeFetch;

    if (lastUpdate > 0) {
        url += "&updatedSince=" + lastUpdate;
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);

    httpGet.setHeader("Accept", "application/json");
    httpGet.setHeader("Accept-Encoding", "gzip");
    httpGet.setHeader(AUTHORIZATION, BEARER + " " + mOAuthToken);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT_STRING);
    httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    HttpResponse response = httpclient.execute(httpGet);

    if (isUnauthorized(response)) {
        APPLICATION.needReauthentication();
        return null;
    }

    if (response != null) {
        InputStream stream = response.getEntity().getContent();
        Header contentEncoding = response.getFirstHeader("Content-Encoding");
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
            stream = new GZIPInputStream(stream);
        }

        InputStreamReader inReader = new InputStreamReader(stream, "UTF-8");
        JsonParser jp = mJsonFactory.createJsonParser(inReader);
        result = getObjectMapper().readValue(jp, SyncVO.class);
    }

    return result;
}

private ObjectMapper getObjectMapper() {
    return (new ObjectMapper()
        .configure(Feature.AUTO_DETECT_FIELDS, true)
        .configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true));
}

最佳答案

不要忘记在每次请求后使用实体内容。

HttpEntity entity = response.getEntity();
  try {
   if (entity != null)
    entity.consumeContent();
  } catch (IOException e) {
   e.printStackTrace();
  }

关于android - Android HTTP客户端卡住,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10199767/

10-10 14:25