网络通信在App的使用中占据重要地位,要实现网络通信,从宏观上分为两种方式,即:调用原生类和使用第三方框架。
调用原生类
Android中通过原生类进行网络通信时,根据业务场景的不同,主要分为两种方式,分别为HTTP网络请求和Socket网络请求,如图所示:

一. Http通信
在Android中发送Http网络请求一般有三种方式,分别为HttpURLConnection、HttpClient和AndroidHttpClient:
1. HttpURLConnection
继承自URLConnection,是 java.net.* 提供的与网络操作相关的标准Java接口,可用于指定URL并发送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网络访问接口,也可以完成Http的GET请求和POST请求,一开始被引入到AndroidAPI中,但在Android在6.0后删除了该类库,如果仍然想要使用,需要在build.gradle文件中进行配置,配置如下:
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.*提供的网络接口,继承自HttpClient常常进行Android特有的网络编程,使用较少。
二. Socket通信
在Android中同样支持Socket通信,是网络通信过程中端点的抽象表示,应用程序与服务器通信可以采用两种模式:TCP可靠通信和UDP不可靠通信。
使用第三方框架
在网络通信过程中,直接使用自带的原生类虽然灵活性比较高,可以根据业务需求进行多种不同配置,但在实际使用中各种功能都需要用户自己去封装定义,因此使用第三方框架就变成了一个很好的选择,常用的第三方框架如下:

okhttp和volley的底层是HttpURLConnection;retrofit是对okhttp的包装,其底层也是HttpURLConnection;android-async-http和xUtils其底层是HttpClient;等其他的第三方库,通过分析可以得到结论,第三方库都是对原生类的功能的封装以及扩展。
一. 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();
}
}
持续更新ing...
网友评论