从java中的一个HTTP请求中读取HTTP响应头和正文

时间:2016-08-22 18:37:13

标签: java http network-programming

在我的程序中,我需要发送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响应标头和正文的示例。

1 个答案:

答案 0 :(得分:1)

我在这个问题上做错了就是打开一个使用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); 从连接中读取。

所以纠正的代码形式是;

    public class func createHorizontalArcPath(_ startPoint:CGPoint, width:CGFloat, arcHeight:CGFloat, closed:Bool = false) -> CGMutablePath
    {
        // http://www.raywenderlich.com/33193/core-graphics-tutorial-arcs-and-paths

        let arcRect = CGRect(x: startPoint.x, y: startPoint.y-arcHeight, width: width, height: arcHeight)

        let arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) / (8*arcRect.size.height));
        let arcCenter = CGPoint(x: arcRect.origin.x + arcRect.size.width/2, y: arcRect.origin.y + arcRadius);

        let angle = acos(arcRect.size.width / (2*arcRadius));
        let startAngle = CGFloat(M_PI)+angle // (180 degrees + angle)
        let endAngle = CGFloat(M_PI*2)-angle // (360 degrees - angle)

        let path = CGMutablePath();
        path.addArc(center: arcCenter, radius: arcRadius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
        if(closed == true)
        {path.addLine(to: startPoint)}
        return path;
    }