Java使用HttpURLConnection上传文件

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:14   2897   0
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MyUpload {
    public static void main(String[] args) {
        String url = "https://api.weixin.qq.com/";
        String fileName = "a.png";
        Path path = Paths.get(fileName);
        byte[] data;
        try {
            data = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String fieldName = "file";
        String s = upload(url, fieldName, fileName, data);
        System.out.println("结果:" + s);
    }

    /**
     * 上传文件
     * 
     * @param strUrl    上传网址
     * @param fieldName 上传文件表单字段名
     * @param fileName  文件名
     * @param data      文件数据
     * @return
     */
    public static String upload(String strUrl, String fieldName, String fileName, byte[] data) {
        String attachmentName = fieldName;
        String attachmentFileName = fileName;
        String crlf = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        try {
            HttpURLConnection httpUrlConnection = null;
            URL url = new URL(strUrl);
            httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setDoOutput(true);
            //
            httpUrlConnection.setRequestMethod("POST");
            httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
            httpUrlConnection.setRequestProperty(
                    "Content-Type", "multipart/form-data;boundary=" + boundary);
            //
            DataOutputStream request = new DataOutputStream(
                    httpUrlConnection.getOutputStream());

            request.writeBytes(twoHyphens + boundary + crlf);
            request.writeBytes("Content-Disposition: form-data; name=\"" +
                    attachmentName + "\";filename=\"" +
                    attachmentFileName + "\"" + crlf);
            request.writeBytes(crlf);
            //
            request.write(data);
            //
            request.writeBytes(crlf);
            request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
            //
            request.flush();
            request.close();
            //
            int code = httpUrlConnection.getResponseCode();
            InputStream is = null;
            if (code == 200) {
                is = httpUrlConnection.getInputStream();
            } else {
                System.out.println("code=" + code);
                is = httpUrlConnection.getErrorStream();
            }
            InputStream responseStream = new BufferedInputStream(is);

            BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));

            String line = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = responseStreamReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            responseStreamReader.close();

            String response = stringBuilder.toString();
            responseStream.close();
            httpUrlConnection.disconnect();
            return response;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP