package com.zhonghong.tsp.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class HttpClientUtil {
private static final Log log = LogFactory.getLog(HttpClientUtil.class);
/**
* HttpClient 模拟spring单点登录后,发送请求URL
*
* @param postUrl
* 请求url
* @param casLoginUrl
* 单点登录url
* @param username
* 登录用户名
* @param password
* 登录密码
* @return
* @throws ServletException
*/
public static String springSecurityRequest(String postUrl,
String casLoginUrl, String username, String password)
throws Exception {
String result = "";
DefaultHttpClient httpclient = HttpConnectionManager.getHttpClient();
String loginIt = doCasLoginRequest(httpclient, casLoginUrl);
// 登录 CAS 身份认证系统
HttpPost httpost = new HttpPost(casLoginUrl);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", username));
nvps.add(new BasicNameValuePair("password", password));
nvps.add(new BasicNameValuePair("lt", loginIt));
nvps.add(new BasicNameValuePair("_eventId", "submit"));
nvps.add(new BasicNameValuePair("submit", "登录"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
writeCookie(httpclient, username);
result = doGetRequest(httpclient, postUrl);
}
httpclient.getConnectionManager().shutdown();
return result;
}
private static String doCasLoginRequest(HttpClient httpclient, String url)
throws IOException {
String result = "";
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader(
entity.getContent(), HTTP.UTF_8));
String tempLine = rd.readLine();
String s = "<input type=\"hidden\" name=\"lt\" value=\"";
while (tempLine != null) {
int index = tempLine.indexOf(s);
if (index != -1) {
String s1 = tempLine.substring(index + s.length());
int index1 = s1.indexOf("\"");
if (index1 != -1)
result = s1.substring(0, index1);
}
tempLine = rd.readLine();
}
if (entity != null) {
entity.consumeContent();
}
return result;
}
private static void writeCookie(DefaultHttpClient httpclient,
String username) throws Exception {
List<Cookie> myCookie = httpclient.getCookieStore().getCookies();
if (myCookie == null || myCookie.size() == 0) {
BasicClientCookie cookie = new BasicClientCookie("ssusername",
username);
// 设置当前容器中的所有页面都可以访问到该Cookie
cookie.setPath("/");
// 设置cookie的有效时间为2小时
CookieStore cookies = httpclient.getCookieStore();
cookies.addCookie(cookie);
httpclient.setCookieStore(cookies);
} else {
boolean flag = false;
for (int i = 0; i < myCookie.size(); i++) {
BasicClientCookie cookie = (BasicClientCookie) myCookie.get(i);
String cookiename = cookie.getName();
if ("ssusername".equals(cookiename)) {
cookie.setValue(username);
flag = true;
break;
}
}
if (!flag) {
BasicClientCookie cookie = new BasicClientCookie("ssusername",
username);
CookieStore cookies = httpclient.getCookieStore();
cookies.addCookie(cookie);
httpclient.setCookieStore(cookies);
}
}
}
private static String doGetRequest(HttpClient httpclient, String url)
throws IOException {
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = toString(entity.getContent(), HTTP.UTF_8);
entity.consumeContent();
}
return result;
}
public static String doGetRequest(String url) throws IOException {
HttpClient httpclient = HttpConnectionManager.getHttpClient();
return doGetRequest(httpclient, url);
}
@SuppressWarnings("rawtypes")
public static String doPostRequest(String url, Map param) {
HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = setNameValuePair(param);
try {
HttpClient httpclient = HttpConnectionManager.getHttpClient();
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
httpost.setHeader("Connection", "close");
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = toString(entity.getContent(), HTTP.UTF_8);
entity.consumeContent();
}
return result;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return "";
}
@SuppressWarnings("rawtypes")
private static List<NameValuePair> setNameValuePair(Map param) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (param == null){
return nvps;
}
Iterator entries = param.entrySet().iterator();
Map.Entry entry;
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
String name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
nvps.add(new BasicNameValuePair(name, ""));
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
nvps.add(new BasicNameValuePair(name, values[i]));
}
} else {
nvps.add(new BasicNameValuePair(name, valueObj.toString()));
}
}
return nvps;
}
private static String toString(InputStream in, String encode) {
StringBuffer result = new StringBuffer();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(in,
encode));
String tempLine = rd.readLine();
while (tempLine != null) {
result.append(tempLine);
tempLine = rd.readLine();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result.toString();
}
public static void sendPost(String url, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String info = doPostRequest(url, request.getParameterMap());
renderHtml(response, info);
}
public static void sendPostJson(String url, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String info = doPostRequest(url, request.getParameterMap());
renderJson(response, info);
}
/**
* 发送文本。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderHtml(HttpServletResponse response, String text) {
render(response, "text/html;charset=UTF-8", text);
}
/**
* 发送文本。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderText(HttpServletResponse response, String text) {
render(response, "text/plain;charset=UTF-8", text);
}
/**
* 发送json。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderJson(HttpServletResponse response, String text) {
render(response, "application/json;charset=UTF-8", text);
}
/**
* 发送xml。使用UTF-8编码。
*
* @param response
* HttpServletResponse
* @param text
* 发送的字符串
*/
public static void renderXml(HttpServletResponse response, String text) {
render(response, "text/xml;charset=UTF-8", text);
}
/**
* 发送内容。使用UTF-8编码。
*
* @param response
* @param contentType
* @param text
*/
public static void render(HttpServletResponse response, String contentType,
String text) {
response.setContentType(contentType);
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
if(text != null){
try {
response.getWriter().write(text);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}