【问题标题】:Is there any simple http response parser for Java?Java有没有简单的http响应解析器?
【发布时间】:2012-02-13 13:10:42
【问题描述】:

有没有简单的http响应解析器实现? 这个想法是将完整的响应作为一个大字符串放入,并能够通过接口检索状态码、正文等内容。

请求/响应不直接通过 TCP/IP 发送,因此除了核心 rfc 2616 解析实现之外不需要任何东西。

【问题讨论】:

    标签: java http


    【解决方案1】:

    如果您使用例如Apache HttpClient,您将获得一个java 响应对象,您可以使用它来提取标题或消息正文。考虑以下示例

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(new HttpGet("http://www.foo.com/"));
    Header[] headers = response.getAllHeaders();
    InputStream responseBody = response.getEntity().getContent();
    

    如果您只想解析响应,也许HttpMessageParser 会很有用:

    旨在从任意数据源构建 HTTP 消息的抽象消息解析器。

    【讨论】:

    • 恕我直言,OP 想要解析他在字符串中的原始 HTTP 响应(可能来自一些转储)。
    • 托马斯是对的。我正在处理原始响应...没有 URI 并且 HttpGet 不起作用。
    • @mibollma,使用HttpMessageParser查看第二个建议
    • 看起来好多了。非常感谢。
    【解决方案2】:

    我推荐 http-request 基于 apache http api。

    HttpRequest<String> httpRequest = HttpRequestBuilder.createGet(someUri, String.class)
        .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
        .build();
    
    public void send(){
       ResponseHandler<String> responseHandler = httpRequest.execute();
       String responseBody = responseHandler.get();
       int statusCode = responseHandler.getStatusCode();
    }
    

    我强烈建议在使用前阅读文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 2018-06-23
      • 2011-01-07
      • 1970-01-01
      • 2020-07-29
      相关资源
      最近更新 更多