安卓中网络请求方式 一.HttpUrlConnection:最基础的,重点
(1)get请求
(2)post请求
(3)get请求数据下载到SD卡中:图片,视频,音频,带进度条的下载
二.HttpClient:已经过时的,安卓SDK26以后该类已经被谷歌删掉了
三.Xutils:第三方框架,功能比较全(数据库,图片,网络。。。。),发明这个东西的人想象很丰满,现实很难维护。
四.OkHttp:第三方框架(重点,老app使用)
这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。
用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)
(1)导入依赖implementation ‘com.squareup.okhttp3:okhttp:3.12.1’
(2)创建Okhttpclient对象
(3)创建Request对象
(4)通过client.newCall(request);得到call对象
(5)调用enqueue方法得到Response对象
五.Volley:第三方框架(重点,老app使用)
(0)导入依赖 implementation’eu.the4thfloor.volley:com.android.volley:2015.05.28’
(1)创建RequestQueue请求队列 (2)创建Request对象:StringRequest和ImageRequest对象
(3)add()添加到请求队列中
六.Retrofit
网络:
private String get_url="http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1";
private String post_url="http://www.qubaobei.com/ios/cf/dish_list.php";//缺少page的请求参数 使用post提交
1.原生网络请求
(1) get请求
private void get() {
new Thread(new Runnable() {
@Override
public void run() {
StringBuffer stringBuffer=new StringBuffer();
try {
URL url = new URL(get_url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5*1000);//链接超时
urlConnection.setReadTimeout(5*1000);//返回数据超时
//getResponseCode (1.200请求成功 2.404请求失败)
if(urlConnection.getResponseCode()==200){
//获得读取流写入
InputStream inputStream = urlConnection.getInputStream();
byte[] bytes=new byte[1024];
int len=0;
while ((len=inputStream.read(bytes))!=-1){
stringBuffer.append(new String(bytes,0,len));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
(2) post请求
private void post() {
new Thread(new Runnable() {
@Override
public void run() {
StringBuffer stringBuffer=new StringBuffer();
try {
URL url = new URL(post_url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5*1000);
urlConnection.setReadTimeout(5*1000);
//设置请求方式,默认是get
urlConnection.setRequestMethod("POST");//大写的POST
//设置允许输出
urlConnection.setDoOutput(true);//允许向服务器提交数据、
//获得输出流写数据 "&page=1"
urlConnection.getOutputStream().write("?stage_id=1&limit=10&page=1".getBytes());//请求参数放到请求体
if(urlConnection.getResponseCode()==200){
InputStream inputStream = urlConnection.getInputStream();
byte[] bytes=new byte[1024];
int len=0;
while ((len=inputStream.read(bytes))!=-1){
stringBuffer.append(new String(bytes,0,len));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
2.xutils
需要导入依赖:
implementation ‘org.xutils:xutils:3.5.1’
3.OkHttp
需要导入依赖:
implementation ‘com.squareup.okhttp3:okhttp:3.12.1’
4.volley
需要导入依赖:
implementation ‘eu.the4thfloor.volley:com.android.volley:2015.05.28’
5.retrofit
个人理解:
retrofit呢也是一种网络框架,他呢底层封装的是OkHttp,也可以理解是OkHttp的加强版,其实底层的网络请求是OkHttp完成的,有疑问说OkHttp来做网络请求,那么,为什么还要封装Retrofit呢,那么retrofit就出来了,Retrofit
仅负责网络请求接口的封装。它的一个特点是包含了特别多注解,方便简化你的代码量。并且还支持很多的开源库(著名例子:Retrofit +
RxJava)。
请求方法
项目 | Value |
---|---|
@GET | GET请求 |
@POST | POST请求 |
请求参数
注解代码 | 说明 |
---|---|
@Headers | 添加请求头 |
@Path | 替换路径 |
@Query | 替代参数值,通常是结合get请求的 |
@FormUrlEncoded | 用表单数据提交 |
@Field | 替换参数值,是结合post请求的 |
那么接下来,就可以看看Retrofit的简单的用法
1.首先我们导入依赖
dependencies {
// Okhttp库
compile 'com.squareup.okhttp3:okhttp:3.1.2'
// Retrofit库
compile 'com.squareup.retrofit2:retrofit:2.0.2'
}
2.创建我们请求的数据类
public class News{
// 比如我们请求到的JSON串,解析类,也就是我们需要的数据
}
3.创建我们的网络请求接口
public interface APi {
// @GET注解的作用:采用Get方法发送网络请求
// getNews(...) = 接收网络请求数据的方法
// 其中返回类型为Call<News>,News是接收数据的类(即上面定义的News类)
// 如果想直接获得Responsebody中的内容,可以定义网络请求返回值为Call<ResponseBody>
@Headers("apikey:81bf9da930c7f9825a3c3383f1d8d766")
@GET("word/word")
Call<News> getNews(@Query("num") String num,@Query("page")String page);
}
4.最后,完成请求
Retrofit retrofit = new Retrofit.Builder()
//设置数据解析器
.addConverterFactory(GsonConverterFactory.create())
//设置网络请求的Url地址
.baseUrl("http://apis.baidu.com/txapi/")
.build();
// 创建网络请求接口的实例
mApi = retrofit.create(APi.class);
//对发送请求进行封装
Call<News> news = mApi.getNews("1", "10");
//发送网络请求(异步)
news.enqueue(new Callback<News>() {
//请求成功时回调
@Override
public void onResponse(Call<News> call, Response<News> response) {
//请求处理,输出结果-response.body().show();
}
@Override
public void onFailure(Call<News> call, Throwable t) {
//请求失败时候的回调
}
});
//发送网络请求(同步)
Response<Reception> response = news.execute();