java 模拟web登陆httpClient并保存cookie

场景:调用接口完成某项操作,但是接口是强登录的,需要cookie, 且cookie会过期;服务器会限制登录的次数,如果一个账号频繁登录,则在短时间内无法正常登录,因此无法做到每调用接口一次就登录一次,且这样的效率也会比较低;

方法: 采用httpClient获取cookie, 并在接口上加入cookie校验;

核心代码:

0. 需要加入的jar包

java 模拟web登陆httpClient并保存cookie

java 模拟web登陆httpClient并保存cookie

1 import org.apache.commons.lang.StringUtils; 2 import org.apache.commons.httpclient.HttpClient; 3 import org.apache.commons.httpclient.methods.GetMethod; 4 import org.apache.http.Header; 5 import org.apache.http.HttpResponse; 6 import org.apache.http.HttpStatus; 7 import org.apache.http.StatusLine; 8 import org.apache.http.client.CookieStore; 9 10 import org.apache.http.client.HttpClient; 11 import org.apache.http.client.methods.HttpGet; 12 import org.apache.commons.httpclient.methods.GetMethod; 13 14 import org.apache.http.client.methods.HttpPost; 15 16 import org.apache.http.cookie.Cookie; 17 import org.apache.http.impl.client.BasicCookieStore; 18 19 import org.apache.http.impl.client.HttpClients; 20 import org.apache.http.protocol.BasicHttpContext; 21 import org.apache.http.protocol.HttpContext;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgyxjd.html