網(wǎng)絡(luò)通信在App的使用中占據(jù)重要地位,要實(shí)現(xiàn)網(wǎng)絡(luò)通信,從宏觀上分為兩種方式血淌,即:調(diào)用原生類和使用第三方框架顽馋。
調(diào)用原生類
Android中通過原生類進(jìn)行網(wǎng)絡(luò)通信時谓厘,根據(jù)業(yè)務(wù)場景的不同,主要分為兩種方式寸谜,分別為HTTP網(wǎng)絡(luò)請求和Socket網(wǎng)絡(luò)請求竟稳,如圖所示:
一. Http通信
在Android中發(fā)送Http網(wǎng)絡(luò)請求一般有三種方式,分別為HttpURLConnection熊痴、HttpClient和AndroidHttpClient:
1. HttpURLConnection
繼承自URLConnection他爸,是 java.net.* 提供的與網(wǎng)絡(luò)操作相關(guān)的標(biāo)準(zhǔn)Java接口,可用于指定URL并發(fā)送GET請求愁拭、POST請求讲逛。
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
connection.connect();
if (connection.getResponseCode() == 200) {
InputStream is = connection.getInputStream();
//do something
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != connection) {
connection.disconnect();
}
}
2. HttpClient
Apache提供的Http網(wǎng)絡(luò)訪問接口,也可以完成Http的GET請求和POST請求岭埠,一開始被引入到AndroidAPI中盏混,但在Android在6.0后刪除了該類庫,如果仍然想要使用惜论,需要在build.gradle文件中進(jìn)行配置许赃,配置如下:
android {
useLibrary 'org.apache.http.legacy'
}
代碼如下:
try {
HttpGet httpGet = new HttpGet("http://www.12306.cn/mormhweb/");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String resultData = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
//do something
}
} catch (Exception e) {
e.printStackTrace();
}
3.AndroidHttpClient
Android.net.*提供的網(wǎng)絡(luò)接口,繼承自HttpClient常常進(jìn)行Android特有的網(wǎng)絡(luò)編程馆类,使用較少混聊。
二. Socket通信
在Android中同樣支持Socket通信,是網(wǎng)絡(luò)通信過程中端點(diǎn)的抽象表示乾巧,應(yīng)用程序與服務(wù)器通信可以采用兩種模式:TCP可靠通信和UDP不可靠通信句喜。
使用第三方框架
在網(wǎng)絡(luò)通信過程中,直接使用自帶的原生類雖然靈活性比較高沟于,可以根據(jù)業(yè)務(wù)需求進(jìn)行多種不同配置咳胃,但在實(shí)際使用中各種功能都需要用戶自己去封裝定義,因此使用第三方框架就變成了一個很好的選擇旷太,常用的第三方框架如下:
okhttp和volley的底層是HttpURLConnection展懈;retrofit是對okhttp的包裝销睁,其底層也是HttpURLConnection;android-async-http和xUtils其底層是HttpClient存崖;等其他的第三方庫冻记,通過分析可以得到結(jié)論,第三方庫都是對原生類的功能的封裝以及擴(kuò)展来惧。
一. OkHttp通信
代碼如下:
OkHttpClient client = null;
Response response = null;
try {
client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build;
Request request = new Request.Builder()
.url(new Url("www.xxx.com"))
.build();
reponse = client.newCall(request).execute();
if(response.isSuccessful()){
//do something
} else {
//do something
}
} catch(Exception e) {
//do something
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.dispatcher().executorService().shutdown();
client.connectionPool().evictAll();
}
}
持續(xù)更新ing...