您的位置:首页 > 编程语言

用代码获取cas服务器的ticket

2015-08-19 00:00 791 查看
摘要: 我们的android弄了好些天都没获取到ticketid,实在看不下去花了俩小时搞到了ticketId

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.client.ClientProtocolException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
* @author 孙林伟
* 用代码获取ticket
*
*/
public class CasTest {

/**
* @param args
* @throws IOException
* @throws ClientProtocolException
*/
public static void main(String[] args) throws ClientProtocolException, IOException {

String[] ltAndEventId = getLtAndEventId("http://localhost:8080/tecoa");
String url = "https://localhost" + ltAndEventId[2];
HashMap<String, Object> param = new HashMap<String, Object>();
param.put("username", "gaohan");
param.put("password", "888888");
param.put("lt", ltAndEventId[0]);
param.put("_eventId", ltAndEventId[1]);
System.out.println(getHttpString(url, param));

}

public static String getHttpString(String url , Map<String,Object> param) throws IOException {
//创建http连接
HttpClient client = new HttpClient();
//创建post请求
PostMethod post = new PostMethod(url);
if(param != null && param.size() > 0){
for (Map.Entry<String,Object> entry : param.entrySet()) {
//添加参数
post.addParameter(entry.getKey(), entry.getValue().toString());
}
}
//设置编码
HttpMethodParams methodParams = post.getParams();
methodParams.setContentCharset("UTF-8");
//执行请求
@SuppressWarnings("unused")
int state = client.executeMethod(post);
post.getResponseBody();
post.getResponseHeaders();
String responseStr = post.getResponseHeader("Location").getValue();
String ticketId = responseStr.substring(responseStr.indexOf("ticket")+7);

return ticketId;
}

public static String[] getLtAndEventId(String url) throws IOException{
Document doc = Jsoup.connect(url).get();
Elements inputs = doc.getElementsByTag("input");
String lt = "",_eventId = "",action = "";
for(Element input : inputs){
if("lt".equals(input.attr("name"))){
lt = input.val();
}
if("_eventId".equals(input.attr("name"))){
_eventId = input.val();
}
}
Element form = doc.getElementById("fm1");
action = form.attr("action");
return new String[]{lt,_eventId,action};
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cas