java里发送请求上传file文件代码收藏

import com.alibaba.fastjson.JSONObject;

import java.io.*;

import java.net.HttpURLConnection;

import java.net.URL;

public class FileUpload {


    public static JSONObject uploadClearFile(File file, String requestUrl){

        JSONObject result = null;

        try{

            String boundary = "Boundary-b1ed-4060-99b9-fca7ff59c113"; //Could be any string

            String Enter = "\r\n";

            FileInputStream fis = new FileInputStream(file);

            URL url = new URL(requestUrl);

            HttpURLConnection conn = (HttpURLConnection)url.openConnection();

            conn.setDoOutput(true);

            conn.setDoInput(true);

            conn.setRequestMethod("POST");

            conn.setUseCaches(false);

            conn.setInstanceFollowRedirects(true);

            conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);

            conn.connect();

            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

            //part 1

            String part1 =  "--" + boundary + Enter

                    + "Content-Type: application/octet-stream" + Enter

                    + "Content-Disposition: form-data; filename=\""+file.getName()+"\"; name=\"file\"" + Enter + Enter;

            //part 2

            String part2 = Enter

                    + "--" + boundary + Enter

                    + "Content-Type: text/plain" + Enter

                    + "Content-Disposition: form-data; name=\"dataFormat\"" + Enter + Enter

                    + "hk" + Enter

                    + "--" + boundary + "--";

            byte[] xmlBytes = new byte[fis.available()];

            fis.read(xmlBytes);

            dos.writeBytes(part1);

            dos.write(xmlBytes);

            dos.writeBytes(part2);

            dos.flush();

            dos.close();

            fis.close();

            System.out.println("status code: "+conn.getResponseCode());

            // 读取返回数据

            StringBuffer strBuf = new StringBuffer();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line = null;

            while ((line = reader.readLine()) != null) {

                strBuf.append(line).append("\n");

            }

            String res = strBuf.toString();

            result = JSONObject.parseObject(res);

            conn.disconnect();

        }catch(Exception e){

            e.printStackTrace();

            return result;

        }

        return result;

    }

}

你可能感兴趣的:(java里发送请求上传file文件代码收藏)