Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将Httpurl连接的响应正确返回到web浏览器_Java_Http_Proxy - Fatal编程技术网

Java 将Httpurl连接的响应正确返回到web浏览器

Java 将Httpurl连接的响应正确返回到web浏览器,java,http,proxy,Java,Http,Proxy,问题:将http消息的响应写回客户端(web浏览器)如果页面在使用字符串时有图像,则不返回完整页面,因此我决定使用字节,但仍然存在相同的问题。我已能够从请求中获取标题作为字符串并将其刷新到客户端,但我不确定如何处理该消息以确保其正确显示在web浏览器上 //This portion takes the message from the Httpurl connection inputstream //the header has already been extt

问题:将http消息的响应写回客户端(web浏览器)如果页面在使用字符串时有图像,则不返回完整页面,因此我决定使用字节,但仍然存在相同的问题。我已能够从请求中获取标题作为字符串并将其刷新到客户端,但我不确定如何处理该消息以确保其正确显示在web浏览器上

        //This portion takes the message from the Httpurl connection inputstream
        //the header has already been exttracted
        //uc here represents a httpurlconnection
       byte[] data = new byte[uc.getContentLength()];
        int bytesRead = 0;
        int offset = 0;
        InputStream in = new BufferedInputStream(uc.getInputStream());
        while (offset < uc.getContentLength()) {
        bytesRead =in.read(data, offset, data.length-offset);
        if (bytesRead == -1) break;
        offset += bytesRead;
//此部分从Httpurl连接inputstream获取消息
//标题已被提取
//uc在这里表示一个httpurlconnection
字节[]数据=新字节[uc.getContentLength()];
int字节读取=0;
整数偏移=0;
InputStream in=新的BufferedInputStream(uc.getInputStream());
while(偏移量
我建议您在读取响应时将字节写入响应,并使用一个小的缓冲区,这样您的服务器就不会受到大内存使用量的影响。将所有字节加载到服务器内存中的数组中不是一个好做法

下面是一个快速示例:

response.setContentType("text/html;charset=UTF-8");
    OutputStream out = response.getOutputStream();
    HttpURLConnection uc;

// Setup the HTTP connection...

InputStream in = uc.getInputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ( bytesRead != -1 ) {
    bytesRead = in.read(b);
    out.write(b);;
}

// Close the streams...

您似乎在用图像代理HTML页面,并且您似乎期望HTML页面中的图像以某种方式自动内联到HTML源代码中。因此,这绝对不是真的。HTML中的图像由
属性表示,该属性指向Web浏览器必须单独调用和下载的URLame故事适用于其他资源,如CSS和JS文件

基本上,您需要解析获得的HTML,扫描所有
(必要时也扫描
)元素,并将它们的URL更改为代理的URL,以便它可以单独为所需的图像(和CSS/JS)资源提供服务


您可以在这个关于一个相关问题的答案中找到一个启动示例:

将响应类型设置为charset=utf-8是我试图避免的。它在某些包含图像的页面上不起作用。这就是我遇到的问题