springboot 后端发送form-data且携带文件的Post请求

338 阅读1分钟

微信新增临时素材,需要请求

http请求方式:POST/FORM
使用https api.weixin.qq.com/cgi-bin/med…

使用java封装一个方法(来源:千锋教育www.56.com/u66/v_MTgzO…)

public static String sendPostByFile(String url, Map<String, String> map, String filePath,String fileName) {  
    HttpPost httpPost = new HttpPost(url);  
    CloseableHttpClient httpClient = HttpClients.createDefault();  
    String resultString = "";  
    CloseableHttpResponse response = null;  
    try{  
        // 把文件转为流对象FileBody  
        FileBody bin = new FileBody(new File(filePath));  
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();  
        builder.addPart(fileName, bin);   
            if (map != null){  
            for (String key : map.keySet()){  
                builder.addPart(key, new StringBody(map.get(key), ContentType.create("text/plain", Consts.UTF_8)));  
            }  
        }  

        HttpEntity reqEntity = builder.build();  
        httpPost.setEntity(reqEntity);  
        // 发送请求,并返回响应  
        response = httpClient.execute(httpPost, HttpClientContext.create());  
        resultString = EntityUtils.toString(response.getEntity(), "utf-8");  
        }catch (Exception e){  
            e.printStackTrace();  
        }finally {  
            try{  
            if(response!=null){  
                response.close();  
            }  
        }catch (IOException e){  
            e.printStackTrace();  
        }  
    }  
    return resultString;  
}