1. 程式人生 > >HttpURLConnection Post請求上傳檔案和引數到servlet

HttpURLConnection Post請求上傳檔案和引數到servlet

public String uplaod(String actionUrl, Map<String, String> params) {
        InputStream in = null;
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri;
        StringBuilder sb2 = null;
        String filePath = params.get("FILE_PATH");
        try {
            uri = new URL(actionUrl);
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();// 設定從主機讀取資料超時
            conn.setReadTimeout(10 * 1000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

            // 首先組拼文字型別的引數
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(PREFFIX);
                sb.append(BOUNDARY);
                sb.append(LINEND);
                sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
                sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
                sb.append(LINEND);
                sb.append(entry.getValue());
                sb.append(LINEND);

            }

            DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
            outStream.write(sb.toString().getBytes(CHARSET));

            // 構建傳送字串資料
            if (!ApplicationUtil.isEmptyString(filePath)) { 
                String fileName = params.get("FILE_NAME");
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream;chartset=" + CHARSET + LINEND);
                sb1.append(LINEND); 
                // 寫入到輸出流中
                outStream.write(sb1.toString().getBytes());

                // 將檔案讀入輸入流中
                InputStream is = new FileInputStream(filePath);
                byte[] buffer = new byte[1024];
                int len = 0;
                // 寫入輸出流
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                is.close(); // 新增換行標誌
                outStream.write(LINEND.getBytes());
            } // 請求結束標誌
            byte[] end_data = (PREFFIX + BOUNDARY + PREFFIX + LINEND).getBytes();
            outStream.write(end_data); // 刷新發送資料
            outStream.flush(); // 得到響應碼
            int res = conn.getResponseCode();

            // 上傳成功返回200
            if (res == 200) {
                in = conn.getInputStream();
                int ch;
                sb2 = new StringBuilder(); // 儲存資料
                while ((ch = in.read()) != -1) {
                    sb2.append((char) ch);
                }
            }
            conn.disconnect();
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (ProtocolException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return sb2 == null ? null : sb2.toString();

    }