●補充說明和程式說明--存取網路資源
=>先開啟網路權限
<uses-permission android:name="android.permission.INTERNET" />
(一)程式流程:當button按下時,抓取google資料,並用log讀出來
public void click1(View view) {
new Thread(){
@Override
public void run()
{
try {
URL url = new URL("http://google.com.tw");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String str;
while ((str=br.readLine()) != null)
{
sb.append(str);
}
String result = sb.toString();
Log.d("mynet","read:"+result);
br.close();
isr.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
**說明:
1.android規定,抓取網路資料要在不同的執行緒,所以要用Thread&override run method
2.起一個URL物件(網址)=>這邊要用try...catch
3.建立連線:HttpURLConnection=>A URLConnection with support for HTTP-specific features.
Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.(用openConnection取得的是OpenConnection物件,要轉成HttpURLConnection物件)
4.openConnection():Returns a URLConnection instance that represents a connection to the remote object referred to by the URL.
5.setRequestMethod(String method):Set the method for the URL request,ex:GET,POST,設定資料傳送方法,一般上網抓資料或看網頁都是用GET,填寫表單傳送是用POST
6.連線 :connect():Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.
7.URLConnection.getInputStream:InputStream getInputStream=>Returns an input stream that reads from this open connection.
=>取到連線物件後,只提供轉成輸入串流的方法
8.透過InputStream(位元組串流)產生InputStreamReader物件,An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset
9.BufferedReader的建構式是BufferedReader(Reader in),而InputStreamReade和FileReader都繼承Reader,所以都可以用來new BufferedReader=>把InputStreamReader轉為BufferedReader,即把網路資料轉成String,這樣就可以使用readLine()
10.最後就是透過while把讀取到的每一行資料放到StringBuilder中,再轉成string,用log顯示,最後就可以看到google網頁的資料如下:
(二)抓取台銀日幣賣出的即期匯率
=>利用String下的indexOf()和substring()來做
=>indexOf
1.public int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character. If a character with value ch occurs in the character sequence represented by this String object, then the index (in Unicode code units) of the first such occurrence is returned.
2.public int indexOf(int ch,int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
=>substring
public String substring(int beginIndex,int endIndex)=>(起始點,終止點的下一個)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
public void click1(View view) {
new Thread(){
@Override
public void run()
{
try {
URL url = new URL("http://rate.bot.com.tw/xrt?Lang=zh-TW";);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String str;
while ((str=br.readLine()) != null)
{
sb.append(str);
}
String result = sb.toString();
int loc1 = result.indexOf("0.2805");
Log.d("LOC1", "loc1:" + loc1);
int loc2 = result.indexOf("日圓 (JPY)");
Log.d("LOC2", "loc2:" + loc2);
int loc3 = result.indexOf("本行現金賣出", loc2);
Log.d("LOC3", "loc3:" + loc3);
int locJPY = loc3 + 56;
String jpy = result.substring(locJPY, locJPY + 6);
Log.d("LOC", "JPY:" + jpy);
br.close();
isr.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
**說明:
1.前面和抓googl一樣,只是網址換成台銀匯率網頁
2.不能直接用indexof抓匯率數字的位置,因為當網頁調整增加一行或甚至只是整數去0,都會影響位置的改變,所以要用別的方法
3.先用while迴圈把所有文字抓近來,再來定位JPY,做法是先找日圓=>再找本行現金賣出=>再推算位置
4.測試(用LOG)0.2805這個匯率的位置(loc1)為27339,如果indexof出來結果為-1,就代表沒讀到資料,可能是因為匯率改變要重查
5.再測試日圓 (JPY)的位置(loc2)為26985,測試從loc2的位置開始找"本行現金賣出"的位置(loc3)為27386(因為每個匯率都有"本行現金賣出",要找日圓後面的)
6.如此就可以計算書從"本行現金賣出"到"日圓即期匯率"的位置距離為loc1-loc3=56(loc3+56),這個是固定的不會被改變
7.因為匯率0.2805總共6個字元,所以當使用substring取字時,就要從locJPY開始取,到(locJPY+6)-1這六個字元
=>上述做法就不用擔心位置會跑掉
**結果:
●程式參考(GitHub):利用HttpURLConnection、InputStream、BufferReader存取網路資源
文章標籤
全站熱搜
留言列表