//将初始url转化为URL对象↓↓
URL url =new URL("http://localhost:8080/vtm1/clientInterface.do?type=downFile");
//打开url连接
HttpURLConnection conn =(HttpURLConnection)url.openConnection();
连接设置
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setREquestProperty("content-type","application/json;chartset=utf-8");
//conn.connect();←在conn.getOutputStream()会隐含的进行connect,所以不调用这个也可以
OutputStream os=conn.getOutputStream();
os.write(message.getBytes());//向输出流写出数据message为要写出的数据,数据将存到内存缓冲区
os.flush();//刷新流
os.close();/关闭流
InputStream is =conn.getInputStream();//将缓存区中封装好的完整的HTTP请求电文发送到服务端
//↑↑↑上面的为实际发送请求的代码段
//将服务器返回的数据流写入指定的文件
final int BUF_LEN = 8192;
byte[] buffer = new byte[BUF_LEN];
OutputStream os = new FileOutputStream("D:/templ/tmp.data");
int nRead = 0;
while (-1 != (nRead = is.read(buffer,0,BUF_LEN))) {
os.write(buffer, 0, nRead);
}
测试文件下载接口代码记录
最新推荐文章于 2024-06-28 16:21:39 发布