首先感谢http://www.zuidaima.com/share/1861712958622720.html对我的帮助,我在此基础上修改了页面的显示,
先上效果吧
public class SearchTrainController implements X509TrustManager { private static String QUERY_RUL = "https://kyfw.12306.cn/otn/lcxxcx/query"; @RequestMapping(value = "searchTrain", method = RequestMethod.POST) public @ResponseBody String searchTrain(HttpServletRequest request/**, HttpServletResponse response, PrintWriter pw*/) { StringBuffer sb = new StringBuffer(); String from_Station = request.getParameter("fromStationText"); String to_station = request.getParameter("toStationText"); String queryDate = request.getParameter("train_start_date"); String purpose_codes = request.getParameter("purpose_codes"); try { TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); String param = "?purpose_codes=" + purpose_codes + "&queryDate=" + queryDate + "&from_station=" + from_Station + "&to_station=" + to_station; System.out.println("URL:"+QUERY_RUL + param); URL url = new URL(QUERY_RUL + param); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(ssf); InputStreamReader in = new InputStreamReader(con.getInputStream(), "utf-8"); BufferedReader bfreader = new BufferedReader(in); String line = ""; while ((line = bfreader.readLine()) != null) { sb.append(line); } //System.out.println(sb.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return sb.toString(); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } }
接下来是我本地写的一个测试类
public class JunitTest { public static void main(String[] args) throws Exception { TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); String urlStr = "https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-06-06&from_station=BXP&to_station=WHN"; URL url = new URL(urlStr); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(ssf); InputStreamReader in = new InputStreamReader(con.getInputStream(), "utf-8"); BufferedReader bfreader = new BufferedReader(in); StringBuffer sb = new StringBuffer(); String line = ""; while ((line = bfreader.readLine()) != null) { sb.append(line); } System.out.println(sb.toString()); } }
这里请求的是12306官网的,这里的请求可能会有token会话,有其他问题的,欢迎留言,主要是练习下。
需要源码的加群哦:188716429