public class GetTickectsFromApi {
private static String tickectUrl = "http://vis.360.cn/open/ticketapi?type=getlines&";
public static void main(String[] args) throws MalformedURLException,
IOException {
getTrainInfoDetail("北京", "河北", "2015-01-30");
}
public static void getTrainInfoDetail(String startProvince,
String endProvince, String date) throws MalformedURLException,
IOException {
String vistUrl = tickectUrl + "depart_date=" + date + "&area="
+ EncodeUtil.encode(startProvince);
String line = getTickectsString(vistUrl);
JSONArray dataJson = JSONArray.fromObject(line);
System.out.println(dataJson);
for (int i = 0; i < dataJson.size(); i++) {
JSONObject info = dataJson.getJSONObject(i);
String startArea = info.getString("start_area");
String endArea = info.getString("end_area");
if (startArea.equals(startProvince) && endArea.equals(endProvince)) {
String startCity = info.getString("start");
String endCity = info.getString("end");
String train = info.getString("train");
String ticket = info.getString("ticket");
System.out.println(startCity + "-->" + endCity + ":" + train
+ ":" + ticket);
}
}
}
public static String getTickectsString(String url)
throws MalformedURLException, IOException {
InputStream in = new URL(url).openStream();
String retLine = IOUtils.readLines(in).get(0);
String line = retLine.substring(1, retLine.length() - 1);
return line;
}
// 暂未使用
public static void getTickectsFile(String url)
throws MalformedURLException, IOException {
InputStream in = new URL(url).openStream();
Writer out = new FileWriter(new File("E:\\DemoTemp\\1.txt"));
try {
IOUtils.copy(in, out, "UTF-8");
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
maven jar包依赖
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.3.5</version> </dependency> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.7.2</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>