這個範例來自於Android學習手冊,該手冊包含9個章節和108個範例。所有的範例都是可互動且可運行的,原始碼採用了Android Studio目錄結構,程式碼部分採用高亮顯示。文件的結構圖能夠幫助快速定位所需內容。你可以透過360手機助理下載該學習手冊,該應用程式的圖示上有一個貝殼標誌。
//第一種
/**取得參數(ArrayListnameValuePairs,String url)後post給遠端伺服器
* 將獲得的回傳結果(String)傳回給呼叫者
* 本函數適用於查詢數量較少的時候
*/
public String posturl(ArrayListnameValuePairs,String url){
String result = "";
String tmp= "";
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
#return "Fail to establish http connection!";
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line "\n");
}
is.close();
tmp=sb.toString();
}catch(Exception e){
#return "Fail to convert net stream!";
}
try{
JSONArray jArray = new JSONArray(tmp);
for(int i=0;iJSONObject json_data = jArray.getJSONObject(i);
Iteratorkeys=json_data.keys();
while(keys.hasNext()){
result = json_data.getString(keys.next().toString());
}
}
}catch(JSONException e){
return "The URL you post is wrong!";
}
return result;
}
需要在AndroidManifest.xml中加權限。
String string = null;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(Uri.parse("content://browser/bookmarks"), new String[]{"url"}, null, null, null);
while (cursor != null & cursor.moveToNext()) {
string = cursor.getString(cursor.getColumnIndex("url"));
Log.d("debug", string == null ? "null":string);
}
展開全部
首先你需要導入:HttpClient、HttpGet
然後透過HttpGet透過url發送request
透過HttpClient的execute取得response
解析傳回的內容
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
以上是取得網頁資料的方法,適用於Android系統的指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!