Javaバックエンドファイルおよびその他のパラメータ付きPostリクエスト

11478 ワード

Javaファイルやその他のパラメータを持つPostリクエストはファイルのアップロードに対して、クライアントは通常ページであり、フロントエンドのwebページでファイルのアップロードを実現するのは難しくない.formを書き、enctype=「multipart/form-data」を加えて、受信したものを書けばいい.難しくない.Javaを使用する場合は.net.HttpURLConnection、javaバックグラウンドでファイルのアップロードを実現するには、本当に頭が痛いです.実現の構想と具体的な手順はページの要求をシミュレートすることです.ページのフォーマットは以下の通りです.name=“luid”
123 -----------------------------7da2e536604c8 Content-Disposition: form-data; name=“file1”; filename=“D:\haha.txt” Content-Type: text/plain
haha hahaha -----------------------------7da2e536604c8 Content-Disposition: form-data; name=“file”; filename=“D:\huhu.png” Content-Type: application/octet-stream
ここでは画像のバイナリデータ--------------------------------------7 da 2 e 536604 c 8–demoコードには2つのパラメータしかなく、1つのFile、1つのString
public static void sendPostWithFile(String filePath) {
        DataOutputStream out = null;
        final String newLine = "\r
"; final String prefix = "--"; try { URL url = new URL("https://ws-di1.sit.cmrh.com/aiisp/v1/mixedInvoiceFileOCR"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); String BOUNDARY = "-------7da2e536604c8"; conn.setRequestMethod("POST"); // POST conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); out = new DataOutputStream(conn.getOutputStream()); // file File file = new File(filePath); StringBuilder sb1 = new StringBuilder(); sb1.append(prefix); sb1.append(BOUNDARY); sb1.append(newLine); sb1.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine); sb1.append("Content-Type:application/octet-stream"); sb1.append(newLine); sb1.append(newLine); out.write(sb1.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); byte[] bufferOut = new byte[1024]; int bytes = 0; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write(newLine.getBytes()); in.close(); // sysName StringBuilder sb = new StringBuilder(); sb.append(prefix); sb.append(BOUNDARY); sb.append(newLine); sb.append("Content-Disposition: form-data;name=\"sysName\""); sb.append(newLine); sb.append(newLine); sb.append("test"); out.write(sb.toString().getBytes()); // returnImage StringBuilder sb2 = new StringBuilder(); sb2.append(newLine); sb2.append(prefix); sb2.append(BOUNDARY); sb2.append(newLine); sb2.append("Content-Disposition: form-data;name=\"returnImage\""); sb2.append(newLine); sb2.append(newLine); sb2.append("false"); out.write(sb2.toString().getBytes()); byte[] end_data = ("\r
--" + BOUNDARY + "--\r
").getBytes(); // out.write(end_data); out.flush(); out.close(); // BufferedReader URL BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (Exception e) { System.out.println(" POST !" + e); e.printStackTrace(); } }

借り【javaバックグラウンドでファイルをアップロードするpostリクエスト(httpとhttps)】
自分でカプセル化したクラス、汎用クラス
/**
 * post     file
 *     
 * JSONObject jp = new JSONObject();
 *  String param = jp.toJSONString()
 */
 public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // URL realUrl = new URL("https://testzoms.txffp.com/pcs/app/common/checkInvoice");
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //   POST          
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            //   BufferedReader      URL   
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
                // System.out.println(result);
            }
        } catch (Exception e) {
            System.out.println("   POST       !" + e);
            e.printStackTrace();
        }
        //   finally       、   
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * post    file,map     
     */
     
    public static JSONObject sendPostWithFile(MultipartFile file, HashMap map) {
        DataOutputStream out = null;
        DataInputStream in = null;
        final String newLine = "\r
"; final String prefix = "--"; JSONObject json = null; PropUtils propUtils = new PropUtils("cfg.properties"); try { String fileOCRUrl = propUtils.getProp("fileOCRUrl"); URL url = new URL(fileOCRUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); String BOUNDARY = "-------KingKe0520a"; conn.setRequestMethod("POST"); // POST conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); out = new DataOutputStream(conn.getOutputStream()); // file // File file = new File(filePath); StringBuilder sb1 = new StringBuilder(); sb1.append(prefix); sb1.append(BOUNDARY); sb1.append(newLine); sb1.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine); sb1.append("Content-Type:application/octet-stream"); sb1.append(newLine); sb1.append(newLine); out.write(sb1.toString().getBytes()); // in = new DataInputStream(new FileInputStream(file)); in = new DataInputStream(file.getInputStream()); byte[] bufferOut = new byte[1024]; int bytes = 0; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write(newLine.getBytes()); StringBuilder sb = new StringBuilder(); int k = 1; for (String key : map.keySet()) { if (k != 1) { sb.append(newLine); } sb.append(prefix); sb.append(BOUNDARY); sb.append(newLine); sb.append("Content-Disposition: form-data;name=" + key + ""); sb.append(newLine); sb.append(newLine); sb.append(map.get(key)); out.write(sb.toString().getBytes()); sb.delete(0, sb.length()); k++; } // sysName /*StringBuilder sb = new StringBuilder(); sb.append(prefix); sb.append(BOUNDARY); sb.append(newLine); sb.append("Content-Disposition: form-data;name=\"sysName\""); sb.append(newLine); sb.append(newLine); sb.append("test"); out.write(sb.toString().getBytes());*/ // returnImage /*StringBuilder sb2 = new StringBuilder(); sb2.append(newLine); sb2.append(prefix); sb2.append(BOUNDARY); sb2.append(newLine); sb2.append("Content-Disposition: form-data;name=\"returnImage\""); sb2.append(newLine); sb2.append(newLine); sb2.append("false"); out.write(sb2.toString().getBytes());*/ byte[] end_data = ("\r
--" + BOUNDARY + "--\r
").getBytes(); out.write(end_data); out.flush(); // BufferedReader URL BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; StringBuffer resultStr = new StringBuffer(); while ((line = reader.readLine()) != null) { resultStr.append(line); } json = (JSONObject)JSONObject.parse(resultStr.toString()); } catch (Exception e) { System.out.println(" POST !" + e); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return json; }
/**
 *        
 * 	  :        getProp()
 * 	new PropUtils(filePath)      ,resources       
 * @author jianbin
 */
public class PropUtils {
	private Properties properties;
	
	public PropUtils(String propertisFile) {
		InputStream in = null;
		try {
			properties = new Properties();
			in = PropUtils.class.getResourceAsStream("/"+propertisFile);
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String getProp(String key){
		return properties.getProperty(key);
	}
	
	/*public static void main(String[] args) {
		PropUtils propUtils = new PropUtils("cfg.properties");
		String str = propUtils.getProp("jobStatus.3");
		System.out.println(str);
	}*/
	
}