java开发调用其它接口上传文件

2023-02-24 08:15:39
     private static final String PREFIX = "--";                            //前缀
    private static final String BOUNDARY = UUID.randomUUID().toString();  //边界标识 随机生成
    private static final String CONTENT_TYPE = "multipart/form-data";     //内容类型
    private static final String LINE_END = "\r\n"; 
//传入file路径
    public void file(String urlName) {
        JSONObject result = new JSONObject();
        JSONObject jsons = new JSONObject();
        jsons.put("key", "value");
        String token=gettoken();
        JSONObject jsonss = null;
        try {
            URL url = new URL("请求接口");
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            OutputStream  out = null;
            //请求方式 这里设置你需要请求的方式
//            conn.setRequestMethod("POST");
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            //这里设置请求头
//            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//            conn.setRequestProperty("Content-Type", "multipart/form-data");

            conn.setRequestProperty("Content-Type", CONTENT_TYPE+";boundary=" + BOUNDARY);
            //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
            //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new DataOutputStream(conn.getOutputStream());
            //你上传上传文件路径
            String path=urlName;
            File file = new File(path);
            String filename = file.getName();
            StringBuilder fileSb = new StringBuilder();
            fileSb.append(PREFIX)
                    .append(BOUNDARY)
                    .append(LINE_END)
                    .append("Content-Disposition: form-data; name=file; filename=" + filename + "" + LINE_END)
                    .append("Content-Type: image/jpg" + LINE_END)
                     .append(LINE_END);
            out.write(fileSb.toString().getBytes());
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);

            //发送请求参数即数据
//            out.print(toJSONString);

            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String str = "";
            String str1="";
            while ((str = br.readLine()) != null) {
                str1 = str1+"\n"+str;
            }
            jsonss = JSONObject.parseObject(str1);
            logger.info("返回json"+jsonss);
            //关闭流
            is.close();
            //操作完以后最好断开连接
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 作者:小菜鸡码代码
  • 原文链接:https://blog.csdn.net/ljy4293/article/details/124152458
    更新时间:2023-02-24 08:15:39