編輯:關於 Android 程式設計
在 Android 上與伺服器交換資料,最基礎的方式之一就是透過 HttpClient 發送 HTTP 請求。本文分別用 HttpGet 與 HttpPost 兩個常見場景,示範如何取得伺服器返回的資料並顯示到畫面上。使用前別忘了在 AndroidManifest.xml 中加入網路權限 <uses-permission android:name="android.permission.INTERNET" />。
GET 適合把參數直接拼接在 URL 後面的查詢場景:
複製程式碼 程式碼如下:
/**
*description:Android HttpGet()
*authour:YanEr·Gates
*website:https://www.jb51.net
*/
package me.gogogoog;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MyHttpGetActivity extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView resultText = (TextView) this.findViewById(R.id.resultText);
String username="username";
String password="password";
String httpUrl = "https://192.168.1.90:8080/AndroidLogin/loginAction.do?method=login&username="+username+"&password="+password;
//創建httpRequest對象
HttpGet httpRequest = new HttpGet(httpUrl);
try
{
//取得HttpClient對象
HttpClient httpclient = new DefaultHttpClient();
//請求HttpClient,取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
//請求成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
//取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
resultText.setText(strResult);
}
else
{
resultText.setText("請求錯誤!");
}
}
catch (ClientProtocolException e)
{
resultText.setText(e.getMessage().toString());
}
catch (IOException e)
{
resultText.setText(e.getMessage().toString());
}
catch (Exception e)
{
resultText.setText(e.getMessage().toString());
}
}
}
POST 則更適合傳送使用者帳密等較敏感或較長的參數,資料放在請求本文中而非 URL:
複製程式碼 程式碼如下:
/**
*description:Android HttpPost()
*authour:YanEr·Gates
*website:https://www.jb51.net
*/
package me.gogogoog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.widget.TextView;
public class ResultActivity extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView resultText = (TextView) this.findViewById(R.id.resultText);
String username="username";
String password="password";
String httpUrl = "https://192.168.1.90:8080/AndroidLogin/loginAction.do?method=login";
//創建httpRequest對象
HttpPost httpRequest = new HttpPost(httpUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
try{
//設置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
//請求httpRequest
httpRequest.setEntity(httpentity);
//取得默認的HttpClient
HttpClient httpclient = new DefaultHttpClient();
//取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
//HttpStatus.SC_OK表示連接成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
resultText.setText(strResult);
}else{
resultText.setText("請求錯誤!");
}
}catch (ClientProtocolException e){
resultText.setText(e.getMessage().toString());
} catch (IOException e){
resultText.setText(e.getMessage().toString());
}catch (Exception e){
resultText.setText(e.getMessage().toString());
}
}
}
兩段程式碼的共同套路是:建立請求物件 → 用 DefaultHttpClient 執行 → 判斷狀態碼是否為 SC_OK → 以 EntityUtils.toString 取出回應字串。差別在於 GET 把參數拼進 URL,而 POST 透過 NameValuePair 清單與 UrlEncodedFormEntity 把參數編碼進本文。
實務提醒:在 Android 4.0 以後,主執行緒不能直接進行網路操作,否則會拋出 NetworkOnMainThreadException。因此實際開發時,請把上述網路請求放到 AsyncTask、Thread 或 Kotlin 協程等非主執行緒中執行,並透過 Handler 等方式把結果回傳到 UI 執行緒更新畫面。
Android 動態添加與設置布局及控件的方法實戰
本文將通過完整實例,講解如何在代碼中動態地添加和設置布局與控件,供大家參考。 有時候我們需要在代碼端動態地設置、添加布局和控件,下面我們就一起來看看該如何處理。直接上代碼
如何編寫一個 Android 友好的 HTML 頁面
在 App 中我們常常需要嵌入一段 HTML 內容(例如協議頁面、幫助文檔),並用 WebView 加載顯示。要讓頁面在手機上呈現良好的排版,關鍵在於正確設置 viewp
從零實作:用 MediaPlayer 與 Service 播放網路音樂
這個範例的目標很明確:讓 App 透過網路串流播放放在 Tomcat 上的 mp3,並提供播放、暫停、停止三顆按鈕。重點不只是 MediaPlayer 的用法,而是把播放
Android 開發之 Monkey 測試——看看你的應用夠不夠健壯
上一篇提到讓應用自動抓取 Crash 日誌並提交到伺服器。其實很多個人在練手時做的小應用,發布前若沒有經過嚴格測試,往往會存在大量顯而易見卻被忽略的錯誤。好在 Andro