java上傳文件和參數到服務器


public static Map<String,Object> uploadFileByHTTP(File postFile,String postUrl,Map<String,String> postParam){
        //Logger log = LoggerFactory.getLogger(UploadTest.class);

        Map<String,Object> resultMap = new HashMap<String,Object>();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try{
            //把一個普通參數和文件上傳給下面這個地址    是一個servlet
            HttpPost httpPost = new HttpPost(postUrl);
            //把文件轉換成流對象FileBody
            FileBody fundFileBin = new FileBody(postFile);
            //設置傳輸參數
            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
            multipartEntity.setCharset(Charset.forName("utf-8"));
            multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntity.addPart(postFile.getName(), fundFileBin);//相當於<input type="file" name="media"/>

            //設計文件以外的參數
            Set<String> keySet = postParam.keySet();
            for (String key : keySet) {
                //相當於<input type="text" name="name" value=name>
                multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("application/json", Consts.UTF_8)));
            }

            HttpEntity reqEntity =  multipartEntity.build();
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(reqEntity);

            //log.info("發起請求的頁面地址 " + httpPost.getRequestLine());
            //發起請求   並返回請求的響應
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                ///log.info("----------------------------------------");
                //打印響應狀態
                //log.info(response.getStatusLine());
                resultMap.put("statusCode", response.getStatusLine().getStatusCode());
                //獲取響應對象
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    //打印響應長度
                    //log.info("Response content length: " + resEntity.getContentLength());
                    //打印響應內容
                    resultMap.put("data", EntityUtils.toString(resEntity,Charset.forName("UTF-8")));
                }
                //銷毀
                EntityUtils.consume(resEntity);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally{
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //log.info("uploadFileByHTTP result:"+resultMap);
        return resultMap;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM