Javaシミュレーションフォームpost提出、画像アップロードをサポート

5042 ワード

/***シミュレーションフォームpost@param textMapテキストドメイン*@param file Mapファイル/
public static String postForm(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) throws IOException {
    String res = "";
    HttpURLConnection conn = null;
    InputStream inS = null;
    OutputStream out = null;
    String BOUNDARY = "---------------------------123821742118716"; //boundary  request            
    try {
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
            ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
        }

        conn.setConnectTimeout(19000);
        conn.setReadTimeout(19000);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        out = new DataOutputStream(conn.getOutputStream());
        // text value
        if (textMap != null) {
            StringBuffer strBuf = new StringBuffer();
            Iterator iter = textMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String inputName = (String) entry.getKey();
                String inputValue = (String) entry.getValue();
                if (inputValue == null) {
                    continue;
                }
                strBuf.append("\r
").append("--").append(BOUNDARY).append("\r
"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r
\r
"); strBuf.append(inputValue); } out.write(strBuf.toString().getBytes()); } // file if (fileMap != null) { Iterator iter = fileMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String inputName = (String) entry.getKey(); String inputValue = (String) entry.getValue(); if (inputValue == null) { continue; } File file = new File(inputValue); String filename = file.getName(); String contentType = new MimetypesFileTypeMap().getContentType(file); if (filename.endsWith(".png")) { contentType = "image/png"; } else if (filename.endsWith(".gif")) { contentType = "image/gif"; } else if (filename.endsWith(".jpg")) { contentType = "image/jpeg"; } if (contentType == null || contentType.equals("")) { contentType = "application/octet-stream"; } StringBuffer strBuf = new StringBuffer(); strBuf.append("\r
").append("--").append(BOUNDARY).append("\r
"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r
"); strBuf.append("Content-Type:" + contentType + "\r
\r
"); out.write(strBuf.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } } } byte[] endData = ("\r
--" + BOUNDARY + "--\r
").getBytes(); out.write(endData); out.flush(); // StringBuffer strBuf = new StringBuffer(); inS = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inS)); String line = null; while ((line = reader.readLine()) != null) { strBuf.append(line).append("
"); } res = strBuf.toString(); reader.close(); reader = null; } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } if (inS != null) { inS.close(); } if (conn != null) { conn.disconnect(); conn = null; } } return res; }