編輯:關於 Android 程式設計
Android 沿用了 JDK 提供的 URL、URLConnection 等網絡通信 API,並在此基礎上引入了更貼合移動端的 HttpURLConnection 與 Apache 的 HttpClient。本文按由底層到上層的順序梳理這套體系。
URL(Uniform Resource Locator,統一資源定位符)是指向互聯網資源的指針,格式為:
protocol://host:port/resourceName
補充一點:JDK 中還有 URI(統一資源標識符)類,它只負責標識資源,不承擔定位職責,兩者用途不同。
拿到 URL 對象後,可以調用一系列方法解析其各部分,或直接訪問對應資源:
String getFile() // 獲取資源文件名
String getHost() // 獲取主機名
String getPath() // 獲取路徑部分
int getPort() // 獲取端口號
String getProtocol() // 獲取協議名
String getQuery() // 獲取查詢字符串
URLConnection openConnection() // 返回表示遠程連接的 URLConnection 對象
InputStream openStream() // 打開連接並返回讀取資源的輸入流
openStream() 是最便捷的下載方式,一行即可拿到資源的輸入流:
public class URLTest extends Activity {
private Bitmap bitmap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
public void run() {
try {
URL url = new URL("https://avatar.csdn.net/D/F/D/1_smartbetter.jpg");
// 解析輸入流中的圖片
InputStream is = url.openStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
// 將圖片下載到本地
is = url.openStream();
OutputStream os = openFileOutput("icon.jpg", MODE_PRIVATE);
byte[] buff = new byte[1024];
int hasRead = 0;
while ((hasRead = is.read(buff)) > 0) {
os.write(buff, 0, hasRead);
}
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
別忘了在清單文件中加入 android.permission.INTERNET 權限,並將網絡操作放到子線程中執行——主線程網絡訪問在較新版本系統上會直接拋出 NetworkOnMainThreadException。
openConnection() 返回的 URLConnection 對象代表應用與遠程資源之間的連接,通過它既能發送請求,也能讀取響應。下面的工具類封裝了 GET 與 POST 兩種請求:
public class GetPostUtil {
/** 向指定 URL 發送 GET 請求
* @param url 請求地址
* @param params 請求參數,形如 name1=value1&name2=value2
* @return 遠程資源的響應 */
public static String doGet(String url, String params) {
String result = "";
BufferedReader in = null;
try {
String urlName = url + "?" + params;
URL realUrl = new URL(urlName);
URLConnection conn = realUrl.openConnection();
// 設置通用請求頭
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.connect();
Map<String, List<String>> map = conn.getHeaderFields();
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (Exception e) {
System.out.println("請求異常!" + e);
} finally {
try {
if (in != null) in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/** 向指定 URL 發送 POST 請求
* @param params 請求參數,形如 name1=value1&name2=value2
* @return 遠程資源的響應 */
public static String doPost(String url, String params) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 發送 POST 請求必須設置以下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(params);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (Exception e) {
System.out.println("請求異常!" + e);
} finally {
try {
if (out != null) out.close();
if (in != null) in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
HttpURLConnection 繼承自 URLConnection,針對 HTTP 協議做了增強,提供了一批便捷方法:
int getResponseCode() // 獲取服務器響應碼
String getResponseMessage() // 獲取響應消息
String getRequestMethod() // 獲取當前請求方法
void setRequestMethod(String m) // 設置請求方法
HttpClient 是 Apache 的開源項目,用於發送 HTTP 請求並接收響應。它不緩存服務器響應、不執行頁面中的 JS、也不做任何 HTML 解析,本質上是增強版的 HttpURLConnection。
public class HttpClientTest extends Activity {
HttpClient httpClient;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpClient = new DefaultHttpClient();
}
/** GET 請求 */
public void doHttpClientGet(View view) {
new Thread() {
@Override
public void run() {
HttpGet get = new HttpGet("https://192.168.1.10:8080/server/page.jsp");
try {
HttpResponse httpResponse = httpClient.execute(get);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
BufferedReader br = new BufferedReader(
new InputStreamReader(entity.getContent()));
String line;
while ((line = br.readLine()) != null) {
System.out.println("服務器響應:" + line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
/** POST 請求,模擬登錄 */
public void doHttpClientPost(View view) {
final String name = "zhangsan";
final String pass = "123";
new Thread() {
@Override
public void run() {
try {
HttpPost post = new HttpPost("https://192.168.1.10:8080/server/login.jsp");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
String msg = EntityUtils.toString(response.getEntity());
System.out.println(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
需要提醒的是,Apache HttpClient 自 Android 5.1 起被標記為廢棄,並在 Android 6.0 中從框架裡移除,新項目不應再依賴它。
工程實踐中更常見的是成熟的三方庫:
它們在連接池複用、攔截器鏈、Gzip 壓縮、異步回調與 API 建模上都有更完善的抽象,能顯著減少重複的樣板代碼。
Android 拋物線下載動畫的製作過程
下載動畫常出現在下載需求較多的 App 中,比如遊戲下載平台、應用市場等。先看看效果圖:實作整個思路是:先把要飛行的圖示(logo)轉成一張 bitmap,建立一個獨立的
Fragment 管理與重疊怪象:add/hide 與 replace 該怎麼選
一、Fragment 是什麼 自從 3.0 引入 Fragment 之後,專案裡用到它的比例越來越高,最典型的場景就是底部 tab 切換內容。首頁的每一個 navigat
Android 簡易實戰:透過廣播接收器為撥打電話加上 IP 前綴
範例目標 這篇實戰以「IP 撥號」為例,說明如何利用自定義廣播接收器,在使用者撥打電話時,於號碼前自動加上預先設定的 IP 線路。 畫面與資料保存 畫面中只需要一個輸入框
Android 官方文件翻譯:把 Eclipse 專案遷移到 Android Studio
翻譯耗時費神,如果你覺得這份譯文還算通順,歡迎按個「推」;若有錯漏之處,也請不吝指正。 Eclipse 專案遷移 把 Eclipse 專案轉成 Android Stud