HTTP请求中的文件参数:通过路径转换文件,实测有效

需求描述:

在进行远程接口调用的时候,对方需要接收文件类参数;但是我们这边只能取到该文件在本服务器中的地址,而无法直接获取到文件传递;想要解决这个问题就只能从该路径中读取到文件信息,然后生成文件。下面展示从路径中读取并生成文件的代码:

通过url进行文件流读取文件

/**
     * 根据URL地址获取文件
     * @param path URL网络地址
     * @return File
     */
    public File getFileByHttpURL(String path){
        String newUrl = path.split("[?]")[0];
        String[] suffix = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = suffix[suffix.length - 1];
        File file = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            file = File.createTempFile("report",fileName);//创建临时文件
            URL urlFile = new URL(newUrl);
            inputStream = urlFile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

http请求示例

public static ResponseVO sendPostByForm(String url, FileVO paramsMap, String token) {
	  String path = "www.baidu.com/a.png";
	  File file = this.getFileByHttpURL(path);
	// 1. 创建HttpRequest对象 - 指定好 url 地址
      HttpRequest httpRequest = new HttpRequest(url);
      ResponseVO response = new ResponseVO();
      // 2. 设置请求方式,默认是GET请求
      httpRequest.setMethod(Method.POST);
      // 3. 设置请求参数   可通过 form表单方法 设置
      //    form方法有很多重载方法,可以一个一个参数设置,也可以将参数封装进一个map集合然后一块儿传
      httpRequest.form("file", file);
      // 4. 设置请求头
      //    请求头同样可以逐一设置,也可以封装到map中再统一设置
      //    设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
//        httpRequest.header("x-c-authorization","yourToken");
      // 5. 执行请求,得到http响应类
      HttpResponse execute;
      try {
          execute = httpRequest.execute();
          log.info("url================================" + httpRequest.getUrl());
          log.info("params================================" + paramsMap);
          log.info("status================================" + execute.getStatus());
          log.info("响应是否成功===========================" + execute.isOk());
          log.info("响应结果===============================" + execute.body());
          // 解析这个http响应类,可以获取到响应主体、cookie、是否请求成功等信息
          String body = execute.body();   // 获取响应主体
          if (execute.isOk()) {
              JSONObject bodyJsonObject = JSON.parseObject(body);// 将获取的响应主体解析成json对象
              int code = bodyJsonObject.getIntValue("code");
              log.info("响应结果code===============================:{}", code);
              String msg = bodyJsonObject.getString("message");
              log.info("响应结果message===============================:{}", msg);
              JSONArray errors = bodyJsonObject.getJSONArray("errors");
              log.info("响应结果errors===============================:{}", errors);
              String data = bodyJsonObject.getString("data");
              log.info("响应结果data===============================:{}", data);
              response.setMessage(msg);
              response.setCode(code);
              response.setData(data);
          } else {
              response.setMessage(body);
              response.setCode(execute.getStatus());
          }
      } catch (Exception e) {
          throw new RuntimeException(e.getLocalizedMessage());
      }
      log.info("response===============================:{}", response);
      return response;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值