关于java模拟登录获取Cookie时经历的坑
springboot 引入jar包版本
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
通过httpclient来模拟登录
代码部分
String loginUrl = "需要调用的接口";
//用来存储cookie的值
CookieStore cookieStore = new BasicCookieStore();
//创建httpClient
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
try {
//根据接口需要的入参添加相对应的数值
Map<String,String> map = Maps.newHashMap();
map.put("userCode","用户名");
map.put("password","密码");
//参数赋值
//根据接口入参类型选择对应的格式。有的是已表单格式提交的,有的是JSON格式提交的,这里要区分开,否则可能调用不成功.
//根据接口入参类型选择对应的格式。有的是已表单格式提交的,有的是JSON格式提交的,这里要区分开,否则可能调用不成功.
//根据接口入参类型选择对应的格式。有的是已表单格式提交的,有的是JSON格式提交的。这里要区分开,否则可能调用不成功(重要的事情说三遍!!!)
//我这里用的是json格式提交的
String data = JSONObject.toJSONString(map);
StringEntity params = new StringEntity(data,"UTF-8");
params.setContentType("UTF-8");
params.setContentType("application/json;charset=UTF-8");
//创建post请求,如果是get建立get请求
HttpPost httpPost = new HttpPost(loginUrl);
//给请求添加入参
httpPost.setEntity(params);
//调用post请求
response = httpClient.execute(httpPost);
//获取返回值(可要,也可不要)
String result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
response.close();
//封装自己需要的cookie格式
if (response.getStatusLine().getStatusCode() == 200) {
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie : cookies) {
String name = cookie.getName();
if (StringUtils.equals("***",name)) {
String value = cookie.getValue();
cookieValue = name+"="+value;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
表单提交部分代码(未测试正确与否,只是找了前辈们的东西过来)
try {
//赋值
List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
valuePairs.add(new BasicNameValuePair("username", name));
valuePairs.add(new BasicNameValuePair("password", password));
//转成相对应的格式
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, "utf-8");
//转换成form表单的编码格式
entity.setContentType("application/x-www-form-urlencoded");
// 创建一个post请求
HttpPost post = new HttpPost(loginUrl);
// 往post里面放入数据
post.setEntity(entity);
//请求访问url
response= httpClient.execute(post);
//释放资源
response.close();
if (response.getStatusLine().getStatusCode() == 200) {
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie : cookies) {
String name = cookie.getName();
if (StringUtils.equals("***",name)) {
String value = cookie.getValue();
cookieValue = name+"="+value;
}
}
}
}
总结
在获取连接的时候一定要注意原接口的调用格式,选择相对应的方法,否则是调用不成功的。我是用自己的血与泪才发现了这个坑。网上很多都是表单提交方式,所以在此着重说明一下。
版权声明:本文为gw_blue原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。