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}; } }