项目场景:

开发中遇到对接需求时候,被要求用post请求传form-data数据的时候一脸懵逼,在postman中可以调用,但是程序中怎么调用呢。


问题描述

在postman中调用是没问题的

 但是在程序中调用就报错了,之前用的是HttpClient的方式请求的

public StringBuffer caller(Map<String,String> map, String strURL) {
        // start
        HttpClient httpClient = new HttpClient();
 
        HttpConnectionManagerParams managerParams = httpClient
                .getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(30000);
        // 设置读数据超时时间(单位毫秒)
        managerParams.setSoTimeout(120000);
 
        PostMethod postMethod = new PostMethod(strURL);
        // 将请求参数的值放入postMethod中
        String strResponse = null;
        StringBuffer buffer = new StringBuffer();
        // end
        try {
            //设置参数到请求对象中
            for(String key : map.keySet()){
                postMethod.addParameter(key, map.get(key));
            }
            
            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode != HttpStatus.SC_OK) {
                throw new IllegalStateException("Method failed: "
                        + postMethod.getStatusLine());
            }
            BufferedReader reader = null;
            reader = new BufferedReader(new InputStreamReader(
                    postMethod.getResponseBodyAsStream(), "UTF-8"));
            while ((strResponse = reader.readLine()) != null) {
                buffer.append(strResponse);
            }
        } catch (Exception ex) {
            throw new IllegalStateException(ex.toString());
        } finally {
            // 释放连接
            postMethod.releaseConnection();
        }
        return buffer;
    }

请求普通的接口没问题,但是第三方的接口会报错:415 Unsupported Media Type ,很明显是请求方式的问题,然后我在请求头加上了multipart/form-data,接口请求通了,但是报错参数错误,也就是接口没获取到参数。

postMethod.setRequestHeader("Content-Type", "multipart/form-data");

原因分析:

form-data主要是以键值对的形式来上传参数,同时参数之间以&分隔符分开。我就尝试利用map进行数据的的封装Map<String,String>,结果发现后台无法正确解析参数,是因为map封装后并不是以&链接的。


解决方案:

最后利用spring来作为后端框架,form-data利用LinkedMultiValueMap对象来包装多个参数,参数以key-value形式,中间以&连接。采用restTemplate代码的实现如下:

public String caller(Map<String,String> map, String strURL){
		HttpHeaders headers = new HttpHeaders();
		MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
		headers.add("Content-Type", "multipart/form-data");
	    //设置参数到请求对象中
        for(String key : map.keySet()){
        	map.add(key, map.get(key));
        }
		
		HttpEntity<MultiValueMap<String, Object>> requestParams = new HttpEntity<>(map, headers);
		ResponseEntity<String> response = restTemplate.postForEntity(apiUrl,requestParams,String.class);
		String result =response.getBody();
		return result;
}

最后没用HttpClient 的方式,改为了restTemplate的方式。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐