【问题标题】:HttpClient get status code [duplicate]HttpClient获取状态码[重复]
【发布时间】:2012-06-06 10:08:45
【问题描述】:

使用 Apache HttpClient 4.1.3 并尝试从 HttpGet 获取状态码:

HttpClient client = new DefaultHttpClient();
HttpGet response = new HttpGet("http://www.example.com");
ResponseHandler<String> handler = new BasicResponseHandler();
String body = client.execute(response, handler);

如何从body 中提取状态码(202、404 等)? 或者,如果在 4.1.3 中有另一种方法可以做到这一点,它是什么?

另外,我假设一个完美/良好的 HTTP 响应是 HttpStatus.SC_ACCEPTED,但也希望对此进行确认。提前致谢!

【问题讨论】:

    标签: java apache-httpclient-4.x


    【解决方案1】:

    编辑:

    尝试:

    HttpResponse httpResp = client.execute(response);
    int code = httpResp.getStatusLine().getStatusCode();
    

    HttpStatus 应该是 200 (HttpStatus.SC_OK)

    (这个问题我读得太快了!)


    尝试:

    GetMethod getMethod = new GetMethod("http://www.example.com");
    int res = client.executeMethod(getMethod);
    

    这应该可以解决问题!

    【讨论】:

    • Enrichman - 谢谢,但它看起来不像 GetMethod 存在于 4.1.3 中 - 有什么想法吗?
    【解决方案2】:

    这个怎么样?

    HttpResponse response = client.execute(getRequest);
    
    // Status Code
    int statusCode = response.getStatusLine().getStatusCode();
    
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    // Response Body
    String responseBody = responseHandler.handleResponse(response);
    

    【讨论】:

      【解决方案3】:

      我喜欢这样做:

      HttpResponse response = client.execute(httppost);
      int status = response.getStatusLine().getStatusCode();
      

      为了将响应主体作为字符串获取,但不使用 responseHandler,我首先将其作为 InputStream:

      InputStream is = response.getEntity().getContent();
      

      然后将其转换为字符串(如何做到这一点here)

      【讨论】:

        猜你喜欢
        • 2019-07-22
        • 2011-02-05
        • 1970-01-01
        • 2021-12-22
        • 2016-02-28
        • 2015-07-21
        • 1970-01-01
        • 1970-01-01
        • 2019-07-20
        相关资源
        最近更新 更多