场景:
提示:这里简述项目相关背景:
http请求调用其三方服务接口,请求方式为form表单。
问题描述
提示:这里描述项目中遇到的问题:
表单中存在重复的key 值,比如说name 字段,重复多个相同的但是value不同,三种方式 三种结果。
一、直接后台拼接字符串,但是第三方服务在一半时候页面打开报错,直接页面返回标签。
拼接后的路径为 :
String url = http://localhost:8080?name=测试1&name=测试2&name=测试3&password=123
HttpResponse httpResponse = HttpRequest.post(url)
.contentType("application/x-www-form-urlencoded")
.charset("utf-8")
.header("Cookie", cookie)
.timeout(10000)
.execute();
二、使用IdentityHashMap成功调用,但是数据错乱,
IdentityHashMap<String, Object> identityHashMap = new IdentityHashMap();
identityHashMap.put(name, "测试1");
identityHashMap.put(name, "测试2");
identityHashMap.put(name, "测试3");
identityHashMap.put(password, 123);
HttpResponse httpResponse = HttpRequest.post(url)
.contentType("application/x-www-form-urlencoded")
.charset("utf-8")
.header("Cookie", cookie)
.form(identityHashMap)
.timeout(10000)
.execute();
三、使用json 成功上传
List<NameValuePair> params = new ArrayList<>();
BasicNameValuePair a = new BasicNameValuePair("name", "测试1");
BasicNameValuePair b = new BasicNameValuePair("name", "测试2");
BasicNameValuePair c = new BasicNameValuePair("name", "测试3");
BasicNameValuePair d = new BasicNameValuePair("password", 123);
params.add(a);
params.add(b);
params.add(c);
params.add(d);
HttpPost post = new HttpPost(url); // 替换为你的目标URL
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(params, "utf-8");
post.setEntity(uefe);
post.setHeader("Cookie", cookie);
// 创建一个http客户端
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 发送post请求
CloseableHttpResponse execute = httpClient.execute(post);
//返回body
String body = EntityUtils.toString(execute.getEntity(), "UTF-8");