12306模拟get方法 ——json解析数据

来源:互联网 发布:文字读取软件 编辑:程序博客网 时间:2024/05/16 14:59

主要难点在于参数的构造,hashmap以及treemap的顺序与插入的顺序不一致,所以只能用list或者用linkedHashmap,其次在于json的解析,尝试过google的gson,不好用,不过有一大优势,gson可以把对象序列化为json,或者从json中构建对象,最后用json解析实现的。

下面是12306get请求的一些参数,主要报告车站号,时间,以及是否是 adult

public static String book_init="https://kyfw.12306.cn/otn/leftTicket/init";public  static final String get_book="https://kyfw.12306.cn/otn/leftTicket/query";public static final  String train_date="leftTicketDTO.train_date";public static final  String from_station="leftTicketDTO.from_station";public static final String to_station="leftTicketDTO.to_station";public static final String purpose="purpose_codes";public static final String audit="ADULT";
接下来则是get的URL的构造,get请求参数会在URL地址中体现出来,post的参数主要在BODY体中

public static String init_url(Map<String,String> params){StringBuilder str=new StringBuilder("?");//还有一个?号,哈哈Set<Map.Entry<String, String>> set=params.entrySet();//Entry en=null;Iterator it=set.iterator();Map.Entry entry;boolean flag=true;while(it.hasNext()){entry=(Entry) it.next();if(flag==false)str.append("&");flag=false;str.append(entry.getKey()+"="+entry.getValue());}
还有一步应为12306为https,所以需要加载证书文件,在Android下面证书文件只能为BKS,可以通过软件keystore 来显示转换

public void init() throws MalformedURLException{   myurl=new URL(url);   try {   //给跪了,java的keytool生成的bks证书也不行fuck      KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());   System.out.println(KeyStore.getDefaultType());   //密钥库的类型可以通过看keytool来查看  trustStore.load(in, "changeit".toCharArray());  //注册密匙库  System.out.println(trustStore.getType());  String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);  tmf.init(trustStore);   // From https://www.washington.edu/itconnect/security/ca/load-der.crt//InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));// Create an SSLContext that uses our TrustManagerSSLContext context = SSLContext.getInstance("TLS");context.init(null, tmf.getTrustManagers(), null);  // Create an SSLContext that uses our TrustManager   //context=SSLContext.   context.init(null, tmf.getTrustManagers(), null);  //Sf.https=(HttpsURLConnection )myurl.openConnection();https.setSSLSocketFactory(context.getSocketFactory());https.setRequestProperty("Accept-Language", "zh-CN");//https.setRequestProperty("contentType", "GBK"); https.setRequestProperty("Charset", "utf-8");if(https==null)System.out.println("https null");if(https.getResponseCode()==https.HTTP_OK){is_ok=true;}elseis_ok=false;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (KeyStoreException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (CertificateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (KeyManagementException e) {// TODO Auto-generated catch blocke.printStackTrace();}   }   public HttpsURLConnection gethttps(){   return https;   }   public boolean gethttp_status(){   return is_ok;   }


最后便是通过java net包或者httpclient包来请求

public class jsontest {private String html;public static String []query={"station_train_code","from_station_name","to_station_name"};public jsontest(String response){html=response;}public static void main(String []args)  {String date="2014-04-16";String train_date="leftTicketDTO.train_date";String from_station="leftTicketDTO.from_station";//leftTicketDTO.train_date=2014-04-16&leftTicketDTO.//from_station=HZH&leftTicketDTO.to_station=CSQ&purpose_codes=ADULT//params.add(new NameValuePair("leftTicketDTO.train_date",data));Map<String,String> params=new LinkedHashMap<String,String>();//treemap,以及hashmap顺序不一定对的,与插入顺序无关params.put(train_date,date);params.put(from_station,"HZH");params.put("leftTicketDTO.to_station", "CSQ");params.put("purpose_codes", "ADULT");getbook get=new getbook(bookInfo.get_book,params);get.init();String response=get.getreponse();     //json myjson=new json();try {JSONObject json=new JSONObject(response);JSONArray data=json.getJSONArray("data");//json比Google的gson好用一点int num=data.length();JSONObject train=null;JSONObject temp=null;String str=null;for(int i=0;i<num;i++){train=data.getJSONObject(i);temp=train.getJSONObject("queryLeftNewDTO");for(int j=0;j<3;j++){str=temp.getString(query[j]);System.out.println(query[j]+":"+str);}}} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}//System.out.println(response);}



1 0
原创粉丝点击