直接上代码:如下是个依赖登录 cookie 的接口
@Test
public void test1()throws Exception{
String api = "/actapi_v2/mapi/member.memberBuy";
Map<String,String> request1 = new HashMap<>();
request1.put("account","18656560102");
request1.put("password","w123456");
Map<String,String> request = new HashMap<>();
request.put("Cookie", UserInfo.Getcookie(request1));
//上一步会打印出cookie
String response = HttpUtils.getInstance().sendHttpRequest("POST",host+api,request);
System.out.println("------------------------"+response);
}
运行后的结果
得到 cookie 的方法
public static String Getcookie(Map<String,String> map) throws Exception {
String api = "/actapi_v2/mapi/user.signIn";
return HttpUtils.getInstance().getSessionCookie(host+api,map);
}
getSessionCookie 方法里
public String getSessionCookie(String url,Map<String,String>maps)throws Exception{
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
CloseableHttpResponse closeableHttpResponse = httpResponse(httpPost);
Header[] headers = closeableHttpResponse.getAllHeaders();
StringBuilder stringBuilder = new StringBuilder();
for (Header header:headers){
HeaderElement[] elements = header.getElements();
for (HeaderElement element:elements){
if (element.getValue() != null && !element.getValue().isEmpty()){
stringBuilder.append(element.getName()).append("=").append(element.getValue()).append(";");
}
}
}
return new String(stringBuilder);
}
不知道运行后为什么会打印出两次 cookie?按理应该一次都出现不了的。感觉是我的 log4j 框架问题?