通過HttpURLConnection連接上傳文件和參數

通過HttpURLConnection鏈接上傳文件和參數,核心代碼及操作步驟

public static String uploadFile(String url, Map<String, String> params, File file) {
        // 換行,或者說是回車
        //final String newLine = "\r\n";
        final String newLine = "\r\n";
        // 固定的前綴
        final String preFix = "--";
        //final String preFix = "";
        // 分界線,就是上面提到的boundary,可以是任意字符串,建議寫長一點,這裏簡單的寫了一個#
        final String bounDary = "----WebKitFormBoundaryCXRtmcVNK0H70msG";
        //final String bounDary = "";
        //請求返回內容
        String output = "";

        try {
            //統一資源定位符
            URL uploadFileUrl = new URL(url);
            //打開http鏈接類
            HttpURLConnection httpURLConnection = (HttpURLConnection) uploadFileUrl.openConnection();
            //設置是否向httpURLConnection輸出
            httpURLConnection.setDoOutput(true);
            //設置請求方法默認爲get
            httpURLConnection.setRequestMethod("POST");
            //Post請求不能使用緩存
            httpURLConnection.setUseCaches(false);
            //設置token
            httpURLConnection.setRequestProperty("authorization", (String) GlobalContext.getSessionAttribute("token"));
            //爲web端請求
            httpURLConnection.setRequestProperty("os", "web");
            //從新設置請求內容類型
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Accept", "*/*");
            httpURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
            //application/json;charset=UTF-8 application/x-www-form-urlencoded
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + bounDary);
            httpURLConnection.setRequestProperty("User-Agent", "(Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36)");


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

            //設置DataOutputStream設置DataOutputStream數據輸出流
            //OutputStream outputStream = httpURLConnection.getOutputStream();

            //上傳普通文本文件
            if (params.size() != 0 && params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    //獲取參數名稱和值
                    String key = entry.getKey();
                    String value = params.get(key);
                    //向請求中寫分割線
                    dos.writeBytes(preFix + bounDary + newLine);
                    //向請求拼接參數
                    //String parm = key + "=" + URLEncoder.encode(value,"utf-8") +"\r\n" ;
                    dos.writeBytes("Content-Disposition: form-data; " + "name=\"" + key + "\"" + newLine);
                    //向請求中拼接空格
                    dos.writeBytes(newLine);
                    //寫入值
                    dos.writeBytes(URLEncoder.encode(value, "utf-8"));
                    //dos.writeBytes(value);
                    //向請求中拼接空格
                    dos.writeBytes(newLine);
                }
            }

            //上傳文件
            if (file != null && !params.isEmpty()) {
                //向請求中寫分割線
                //把file裝換成byte
                File del = new File(file.toURI());
                InputStream inputStream = new FileInputStream(del);
                byte[] bytes= input2byte(inputStream);
                String filePrams = "file";
                String fileName = file.getName();
                //向請求中加入分隔符號
                dos.write((preFix + bounDary + newLine).getBytes());
                //將byte寫入
                dos.writeBytes("Content-Disposition: form-data; " + "name=\"" + URLEncoder.encode(filePrams, "utf-8") + "\"" + "; filename=\"" + URLEncoder.encode(fileName, "utf-8") + "\"" + newLine);
                dos.writeBytes(newLine);
                dos.write(bytes);
                //向請求中拼接空格
                dos.writeBytes(newLine);
            }
            dos.writeBytes(preFix + bounDary + preFix + newLine);
            //請求完成後關閉流
            //得到相應碼
            dos.flush();
            //判斷請求沒有成功
            if (httpURLConnection.getResponseCode() != 200) {
                logger.error(url + "   請求異常,錯誤代碼爲:  " + httpURLConnection.getResponseCode());
                return "{result:'fail',response:'errorCode:" + httpURLConnection.getResponseCode() + "'}";
            }
            //判斷請求成功
            if (httpURLConnection.getResponseCode() == 200) {
                //將服務器的數據轉化返回到客戶端
                InputStream inputStream = httpURLConnection.getInputStream();
                byte[] bytes = new byte[0];
                bytes = new byte[inputStream.available()];
                inputStream.read(bytes);
                output = new String(bytes);
                inputStream.close();
            }
            dos.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(url + "   請求異常,錯誤信息爲:  " + e.getMessage());
            return "{result:'fail',response:'" + e.getMessage() + "'}";
        }
        return output;
    }

    /**
     * 將輸入流轉化成字節流
     * @param inStream
     * @return
     * @throws IOException
     */
    public static final byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章