postman的code
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.0</version>
</dependency>
@RequestMapping("getcookie")
@ResponseBody
public String updateCookie(){
JSONObject json = new JSONObject();
json.put("username",loginName);
json.put("password",password);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,String.valueOf(json));
Request request = new Request.Builder()
.url(loginUrl)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
//判断是否成功
if(response.code()==200){
List<String> Cookies= response.headers("Set-Cookie");
for(String str:Cookies){
if(str.startsWith("JSESSIONID")){
JSESSIONID = getJsessionId(str);
return JSESSIONID;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String getJsessionId(String value){
if(null == value){
return null;
}
return value.split(";")[0].split("=")[1];
}