天天看點

java form-data格式上傳檔案或檔案二進制流

1.上傳檔案

String result="";
        PostMethod post = new PostMethod(url);
        Part[] parts = { new StringPart("token", "1F019648B56CF2C2A380248ED6F4A650"),  
        						new StringPart("key", "111111111111111"),
                   			    new FilePart("file",new file(filePath)};
        try {
            HttpClient httpclient = new HttpClient();
            MultipartRequestEntity entity = new MultipartRequestEntity( parts, post.getParams());
            post.setRequestEntity(entity);
            int code = httpclient.executeMethod(post);
            //拿到響應結果
            result = new String(post.getResponseBody(), "UTF-8");
        }catch (Exception e){
            logger.error("post請求出現異常:"+e);
        }finally {
            if (post!=null){
                //可釋放連接配接
                post.releaseConnection();
            }
        }
        return result;
           

2.上傳檔案二進制流

Part[] parts = { new StringPart("token", "1F019648B56CF2C2A380248ED6F4A650"),  
        		 new StringPart("key", customerNo),
                 new FilePart("file",new ByteArrayPartSource("file",bytes))}