因爲以前在公司一直用的C#作的軟件開發,近些天有同窗須要用Java作一個從指定網址獲取信息的Java程序。正好不是很難,順便複習了一下Java的知識。html
要求以下,在https://www.marinetraffic.com/en/ais/details/ships/shipid:650235/mmsi:414726000/vessel:YU%20MING網址中獲得以下圖框中標記的數據。java
程序以下:GetWebPosition類是主要程序類git
package yinhang.wang;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
public class GetWebPosition {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String info = GetDataByTwo();
System.out.println(info);
}
// 從指定的url中獲取數據
//https://www.marinetraffic.com/en/ais/details/ships/shipid:650235/mmsi:414726000/vessel:YU%20MING
private static String HttpRequest(String requestUrl) {
StringBuffer buffer = null;
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
InputStream inputStream = null;
HttpsURLConnection httpUrlConn = null;
// 創建並向網頁發送請求
try {
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 從上述SSLContext對象中獲得SSLSocketFactory對象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
// 描述狀態
httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn
.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36)");
//防止報403錯誤。
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 請求的類型
httpUrlConn.setRequestMethod("GET");
// 獲取輸入流
inputStream = httpUrlConn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
// 從輸入流讀取結果
buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 釋放資源
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpUrlConn != null) {
httpUrlConn.disconnect();
}
}
return buffer.toString();
}
private static String HtmlFiter(String html) {
StringBuffer buffer = new StringBuffer();
String str1 = "";
String str2 = "";
//取出所用的範圍,
//Pattern p = Pattern.compile("(.*)(<div class=\"panel panel-primary no-border vertical-offset-20\">)(.*)(</div>)(.*)");
Pattern p = Pattern.compile("(.*)(</script>)(.*)(<div class=\"wind_icon wind_low\")(.*)");
Matcher m = p.matcher(html);
if (m.matches()) {
str1 = m.group(3);
//取得時間:Vessel's Local Time:
p = Pattern.compile("(.*)(time datetime=\")(.*)(\">)(.*)(</time>)(.*)(</span></strong>)(.*)");
m = p.matcher(str1);
if (m.matches()) {
str2 = m.group(5);
String str3 = m.group(7);
buffer.append("\nVessel's Local Time: ");
buffer.append(str2);
buffer.append(str3);
}
// <a href="/en/ais/home/centerx:120.3903/centery:32.02979/zoom:10/mmsi:414726000/shipid:650235"
// class="details_data_link">32.02979° / 120.3903°</a>
//取得當前經緯度:Latitude / Longitude:
p = Pattern.compile("(.*)(class=\"details_data_link\">)(.*)(</a></strong></span>)(.*)");
m = p.matcher(str1);
if (m.matches()) {
str2 = m.group(3);
buffer.append("\nLatitude / Longitude: ");
buffer.append(str2);
}
//取得當前速度航線Speed/Course:
p = Pattern.compile("(.*)(<span><strong>)(.*)(</strong></span>)(.*)");
m = p.matcher(str1);
if (m.matches()) {
str2 = m.group(3);
buffer.append("\nSpeed/Course: ");
buffer.append(str2);
}
}
return buffer.toString();
}正則表達式
//封裝上述兩個方法
public static String GetDataByTwo(){
//調用第一個方法,得到html字符串
String html = HttpRequest("https://www.marinetraffic.com/en/ais/details/ships/shipid:650235/mmsi:414726000/vessel:YU%20MING");
//調用第二個方法,過濾掉無用的信息
String result = HtmlFiter(html);
return result;
}
}安全
MyX509TrustManager這個類的做用是提供安全證書去訪問https類型 的網站app
package yinhang.wang;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}dom
但願初步學習正則表達式和爬數據的小夥伴們可以用到。
學習