在這裡把三種擷取網頁內容的資訊進行了綜合,在前面已經對通過表單提交上傳檔案進行了處理,現在把這三種方式進行了綜合,放到一塊,協助大家進行一個比較,下面為三種方式 的部分代碼:
一共三個函數,都可以直接調用,但是在訪問網路的時候,記得要加上存取權限
代碼
// 直接擷取資訊
void DirectInfo() throws IOException {
URL url = new URL(SRC);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
InputStreamReader inStreamReader = new InputStreamReader(httpConn
.getInputStream());
BufferedReader bufReader = new BufferedReader(inStreamReader);
String line = "";
String Date = "OK";
while ((line = bufReader.readLine()) != null) {
Date += line + "\n";
}
edit1.setText(Date);
}
// get方式擷取資訊
void getInfo() throws IOException {
// 將上面使用的方法直接修改一下即可。
URL url = new URL(SRC+"/default.aspx?NAME="
+ URLEncoder.encode("abc", "utf-8"));
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
InputStreamReader inputReader = new InputStreamReader(httpconn
.getInputStream());
BufferedReader bufReader = new BufferedReader(inputReader);
String line = "";
String Date = "";
while ((line = bufReader.readLine()) != null) {
Date += line;
}
edit1.setText(Date);
}
// Post方式擷取資訊
void postInfo() throws MalformedURLException, IOException {
// Post 方法比Get方法需要設定的參數更多
HttpURLConnection httpconn = (HttpURLConnection) new URL(SRC)
.openConnection();
// post 方式,輸入輸出需要設定為true
httpconn.setDoInput(true);
httpconn.setDoOutput(true);
httpconn.setRequestMethod("POST"); // 設定為Post方式,預設為get方式
httpconn.setUseCaches(false); // 不使用緩衝
httpconn.setInstanceFollowRedirects(true); // 重新導向
httpconn.setRequestProperty("Content-type",
"Application/x-www-form-urlencoded"); // 設定串連 的Content-type類型為:
// application/x-www-form-urlencoded
httpconn.connect(); //串連
DataOutputStream out = new DataOutputStream(httpconn.getOutputStream()); //聲明資料寫入流
String content = "NAME="+URLEncoder.encode("fly_binbin", "gb2312");
out.writeBytes(content);
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
String line = "";
String resultDate = "";
while((line=reader.readLine())!=null)
{
resultDate += line;
}
edit1.setText(resultDate);
}
網址的話,可以自己做一個測試伺服器。我這個測試伺服器是我自己寫的,進行測試用的,用Asp.net寫的,用其它的方法寫的結果是一樣的。包括使用Web服務結果也是一樣的!