根据url下载文件字节码


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 文件上传
     *
     * @param httpUrl 文件上传的url
     * @param params  传递的参数
     * @param headers
     * @return
     */
    @SuppressWarnings("finally")
    public static byte[] downloadFile(String httpUrl, String params, Map<String, Object> headers) {
        DataOutputStream ds = null;
        BufferedInputStream in = null;
        ByteArrayOutputStream bos = null;
        try {
            // 统一资源
            URL url = new URL(httpUrl);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpURLConnection.setDoInput(true);
            // 设置是否向httpUrlConnection输出
            httpURLConnection.setDoOutput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码连接参数
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置请求内容类型
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            //设置header
            httpURLConnection.setRequestProperty("X-CC-Key-ID", String.valueOf(headers.get("X-CC-Key-ID")));
            httpURLConnection.setRequestProperty("X-CC-Auth-Key", String.valueOf(headers.get("X-CC-Auth-Key")));

            // 设置DataOutputStream
            ds = new DataOutputStream(httpURLConnection.getOutputStream());

            //======传递参数======
            ds.write(params.getBytes());
            //======传递参数end======
            ds.flush();
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                bos = new ByteArrayOutputStream(10288);
                in = new BufferedInputStream(httpURLConnection.getInputStream());
                int buf_size = 1024;
                byte[] buffer = new byte[buf_size];
                int len;
                while (-1 != (len = in.read(buffer, 0, buf_size))) {
                    bos.write(buffer, 0, len);
                }
                return bos.toByteArray();
            } else {
                throw new Exception(httpURLConnection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ds != null) {
                    ds.close();
                }
                if (in != null) {
                    in.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这可能是由于以下原因导致的: 1. 没有正确设置Content-Type头部,应该设置为multipart/form-data。 2. 没有正确设置boundary,boundary是用来分隔不同的表单字段和文件的。 3. 没有正确设置Content-Disposition头部,应该设置为form-data,并指定name和filename属性。 4. 没有正确读取文件字节码,应该使用FileInputStream或者ByteArrayInputStream来读取文件字节码。 你可以参考以下代码来发送formdata: ``` URL url = new URL("http://example.com/upload"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes("--" + boundary + "\r\n"); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n"); dos.writeBytes("Content-Type: " + mimeType + "\r\n"); dos.writeBytes("\r\n"); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { dos.write(buffer, 0, bytesRead); } fis.close(); dos.writeBytes("\r\n--" + boundary + "--\r\n"); dos.flush(); dos.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 文件上传成功 } ``` 注意,这只是一个示例代码,你需要根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值