【问题标题】:Where can I get http response code from HttpClient returned from Twitter search?我在哪里可以从 Twitter 搜索返回的 HttpClient 获取 http 响应代码?
【发布时间】:2012-12-06 09:32:09
【问题描述】:

我正在调用 Twitter 搜索并获得 JSON 响应。我的理解是,如果超过 twitter 请求限制,这将在 HttpResponse 代码中报告。发出请求后如何从 HttpClient 类中获取响应码?

还有谁知道这是否真的是 twitter 报告超出速率限制的方式?

    import org.apache.http.client.HttpClient;
            import org.apache.http.client.ResponseHandler;
            import org.apache.http.client.methods.HttpGet;
            import org.apache.http.impl.client.BasicResponseHandler;
            import org.apache.http.impl.client.DefaultHttpClient;

    HttpGet get = new HttpGet(searchUrl); 
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = null;
    try{
        responseBody = client.execute(get, responseHandler);
                    // How can I get HTTP response code?
    }
    catch(Exception ex) 
    {
        ex.printStackTrace();
    }

【问题讨论】:

  • 运行时你的响应字符串为空?
  • 否,但它不会包含 HTTP 响应代码。它包含一个数据字符串。
  • 查看下面的帖子,很有希望

标签: java android twitter twitter4j


【解决方案1】:

根本不要使用响应处理程序 - 您可以使用 HttpResponse#getStatusLine() 从普通的 HttpResponse 实例获取状态代码:

HttpGet get = new HttpGet(searchUrl); 
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpResponse response = client.execute(get);
int statusCode = response.getStatusLine().getStatusCode();

推荐阅读:


注意BasicResponseHandler返回String而不是抛出异常时,这意味着响应代码是2xx(即200 &lt;= code &lt; 300)。

【讨论】:

    猜你喜欢
    • 2016-10-21
    • 2018-06-27
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 2013-06-14
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多