【问题标题】:Read HTTP response header and body from one HTTP request in java从 Java 中的一个 HTTP 请求中读取 HTTP 响应标头和正文
【发布时间】:2016-08-22 18:37:12
【问题描述】:

在我的程序中,我需要发送一个 HTTP 请求并读取 HTTP 响应正文和标头。

所以我把这些例子加在一起如下;

URL obj = new URL("http://localhost:8080/SpringSecurity/admin");
URLConnection conn = obj.openConnection();

//get all headers
Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
}        
ByteArrayOutputStream output = (ByteArrayOutputStream) conn.getOutputStream();        

byte[] input = output.toByteArray();         
System.out.println(input.length);

打印标题但不打印字节数组input的长度。

谁能解释为什么会发生这种情况以及读取 HTTP 响应标头和正文的示例。

【问题讨论】:

    标签: java http network-programming


    【解决方案1】:

    我在这个问题中做错的是打开一个输出流,该流使用conn.getOutputStream() 写入连接。所以我打开了一个输入流,它使用conn.getInputStream() 从连接中读取。

    所以正确的代码形式是;

    URL obj = new URL("http://localhost:8080/SpringSecurity/admin");          
    URLConnection conn = obj.openConnection();
    
    //get all response headers
    Map<String, List<String>> map = conn.getHeaderFields();
    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
    }
    
    //get response body
    InputStream output = conn.getInputStream();
    Scanner s = new Scanner(output).useDelimiter("\\A");
    String result = s.hasNext() ? s.next() : "";
    System.out.println(result);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    相关资源
    最近更新 更多