尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

边读边写,流式中继

边读边写,流式中继 流式中继publicvoidrelay(PathVariableStringfileId,ServletResponseservletResponse)throwsException{// 1. 从 A 获取流URLurlnewURL(http://A/download/fileId);URLConnectionconnurl.openConnection();InputStreamaInconn.getInputStream();// 2. 打开 B 的输出流HTTP chunkedURLbUrlnewURL(http://B/upload);HttpURLConnectionbConn(HttpURLConnection)bUrl.openConnection();bConn.setDoOutput(true);bConn.setFixedLengthStreamingMode(conn.getContentLength());bConn.setRequestProperty(Content-Type,application/octet-stream);OutputStreambOutbConn.getOutputStream();// 3. 边读边写核心byte[]buffernewbyte[8*1024];longtotal0;intlen;while((lenaIn.read(buffer))!-1){bOut.write(buffer,0,len);totallen;}bOut.flush();bOut.close();aIn.close();// 4. 可选检查 B 响应if(bConn.getResponseCode()!200){thrownewRuntimeException(B upload failed);}}
返回列表