public Object userLogin(HttpServletRequest request, HttpServletResponse response, String email, String password,
String captcha) {
//获取sessionId
String jsessionIdSt = getCookieStringByKey(request, "JSESSIONID"
);
if (StringUtils.isEmpty(jsessionIdSt)) {
return ResultVOUtil.retFailed("登录缓存信息为空"
);
}
if (StringUtils.isNotBlank(jsessionIdSt)) {
if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password) ||
StringUtils.isEmpty(captcha)) {
ResultVOUtil.retFailed("用户名/用户密码/验证码不能为空"
);
}
// 创建默认的httpClient实例.
CloseableHttpClient httpclient =
HttpClients.createDefault();
// 创建请求方法实例
HttpPost httpPost =
new HttpPost("http://www.test.com/user/login");
CloseableHttpResponse innerResponse =
null;
HttpEntity entity =
null;
httpPost.addHeader(new BasicHeader("Cookie", "JSESSIONID=" +
jsessionIdSt));
// 创建参数队列
List<NameValuePair> formparams =
new ArrayList<NameValuePair>
();
formparams.add(new BasicNameValuePair("email"
, email));
formparams.add(new BasicNameValuePair("password"
, password));
UrlEncodedFormEntity uefEntity;
try {
uefEntity =
new UrlEncodedFormEntity(formparams, "UTF-8"
);
httpPost.setEntity(uefEntity);
// 发送请求并接收response
innerResponse =
httpclient.execute(httpPost);
//解析response
entity =
innerResponse.getEntity();
if (entity !=
null) {
// 成功
String ssoResultSt =
EntityUtils.toString(entity, CHAR_SET_UTF_8);
JSONObject ssoResultJson =
JSONObject.parseObject(ssoResultSt);
String ssoData = ssoResultJson.getString("data"
);
Integer ssoCode = ssoResultJson.getInteger("code"
);
String ssoMsg = ssoResultJson.getString("msg"
);
if (ssoCode ==
null) {
return ResultVOUtil.retFailed("SSO登录返回状态为空"
);
}
// 登录成功,返回码为预设的值
if (ssoCode.intValue() ==
1) {
// response植入cookie
Header[] ssoResponseHeader = innerResponse.getHeaders("Set-Cookie"
);
if (ssoResponseHeader !=
null && ssoResponseHeader.length != 0
) {
for (Header stepHeader : ssoResponseHeader) {
if (stepHeader !=
null) {
response.addHeader(stepHeader.getName(), stepHeader.getValue());
}
}
}
return ResultVOUtil.retSuccess(ssoData);
}
// 登录失败
else {
return ResultVOUtil.retFailed(ssoMsg);
}
} else {
return ResultVOUtil.retFailed("登录端没有响应"
);
}
} catch (ClientProtocolException protocolException) {
logger.error(protocolException.getMessage(), protocolException);
} catch (UnsupportedEncodingException uException) {
logger.error(uException.getMessage(), uException);
} catch (IOException ioException) {
logger.error(ioException.getMessage(), ioException);
} finally {
// 关闭连接,释放资源
try {
if (innerResponse !=
null) {
innerResponse.close();
}
httpclient.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
return ResultVOUtil.retFailed("业务异常,导致登录失败"
);
} else {
return ResultVOUtil.retFailed("缓存信息丢失"
);
}
}
转载于:https://www.cnblogs.com/sonofelice/p/5089766.html