对账单文件下载都可以用到 微信对账单 GZIP 文件返回

  • 在看到这个文章之前很多同学都是在用HttpClient 请求操作的,这里就进入了一个误区,也不是说用HttpClient不行,我也把文件下载下来了,但是内容中多出了很多乱码,不知道是什么东西,如果你能用HttpClient请求下载成功无乱码欢迎分享经验.
  • 这里最终是用HttpURLConnection 建立TCP连接  与服务器进行交互的.下面我就贴出代码
      /*** * @param urlPath 请求地址* @param saveUrl 保存文件地址* @param data 请求参数* @return* @throws IOException* @throws Exception*/public static void downFile(String urlPath, String saveUrl, String data) throws IOException {// 设置访问地址URL url = new URL(urlPath);// 连接类的父类,抽象类URLConnection urlConnection = url.openConnection();// http的连接类 得到网络访问对象HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;// 设置请求参数(访问方式,超时时间,输入,输出流,请求头信息),以流的形式进行连接// 设定请求的方法,默认是GEThttpURLConnection.setRequestMethod("POST");// 超时时间httpURLConnection.setConnectTimeout(3000);// 设置是否向HttpURLConnection输出httpURLConnection.setDoOutput(true);// 设置是否从httpUrlConnection读入httpURLConnection.setDoInput(true);// 设置使用编码格式参数的名-值对httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");// 简历连接httpURLConnection.connect();// 写入参数到请求中BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));// 传递参数writer.write(data.toString());writer.flush();writer.close();// 获取响应code 200成功int code = httpURLConnection.getResponseCode();if (code == 200) {InputStream inputStream = httpURLConnection.getInputStream();// 判断字节大小if (inputStream.available() != 0) {System.out.println("结果大小:" + inputStream.available());File file = new File(saveUrl);if (!file.getParentFile().exists()) {boolean result = file.getParentFile().mkdirs();if (!result) {System.out.println("创建失败");}}OutputStream out = new FileOutputStream(file);int size = 0;int len = 0;byte[] buf = new byte[1024];while ((size = inputStream.read(buf)) != -1) {len += size;out.write(buf, 0, size);}System.out.println("最终写入字节数大小:" + len);inputStream.close();out.close();}}// 关闭 http连接,释放资源httpURLConnection.disconnect();}

     


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部