项目场景
开发中遇到对接需求时候,被要求用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的方式。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论