HTTP POST请求发送form-data格式的数据

1、业务需求

发送请求给第三方服务的接口,且请求报文格式为multipart/form-data的数据。支持复杂类型的参数,包含文件类型

2、 依赖包

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.58</version>
		</dependency>
		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>

3、 请求方式实现

/**
     * post请求发送form-data格式的数据
     * @param url  	请求url
     * @param param 请求参数
     * @param clazz 请求类型
     * @return
     */
    public static <T> T doPostFormData(String url, Map<String, Object> param,Class<T> clazz) {
    
    
        return doPostFormData(url, param,new TypeReference<T>() {
    
    
			@Override
			public Type getType() {
    
    
				return clazz;
			}
		});
    }
    
	/**
     * post请求发送form-data格式的数据
     * @param url  	请求url
     * @param param 请求参数
     * @param type 请求类型
     * @return
     */
    public static <T> T doPostFormData(String url, Map<String, Object> param,TypeReference<T> type) {
    
    
        // 创建Http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建HttpPost实例
        HttpPost httpPost = new HttpPost(url);
       
        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);
       
        try {
    
    
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //表单中其他参数
           if(param != null) {
    
    
        	   for(Map.Entry<String, Object> entry: param.entrySet()) {
    
    
        		   Object value = entry.getValue();
        		   System.err.println(entry.getKey());
                   if(value instanceof File) {
    
    
                	   // 文件流
                	   builder.addBinaryBody(entry.getKey(), (File)value);
                   }else {
    
    
                	   builder.addPart(entry.getKey(),new StringBody(String.valueOf(entry.getValue()), ContentType.create("text/plain", Consts.UTF_8)));   
                   }
                   
               }
           }
           
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
    
    
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                return JSON.parseObject(res).toJavaObject(type);
            }
           
        } catch (Exception e) {
    
    
            e.printStackTrace();
            log.error("调用HttpPost失败!" ,e);
        } finally {
    
    
            if (httpClient != null) {
    
    
                try {
    
    
                    httpClient.close();
                } catch (IOException e) {
    
    
                	log.error("关闭HttpPost连接失败!",e);
                }
            }
        }       
        return null;
    }

4、 其他

4.1、 MultipartFile对象转换File对象

4.1.1、 依赖包

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.6</version>
		</dependency>

4.1.1、 实现

	public static File getFile(String path,MultipartFile multipartFile) {
    
    
		try {
    
    
			File file = new File(path); 
			FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
			return file;
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
		return null;
	}

猜你喜欢

转载自blog.csdn.net/qq_43432189/article/details/130563323