网络请求方式:
- GET : 向服务器发起数据请求,获取信息。类似于数据库的select操作,只是查询,不会影响资源的内容。
- POST : 向服务器发送数据,该请求会改变数据的种类等资源。类似于数据库的insert操作,会创建新的内容。
- DELETE:用来删除某一个资源。类似于数据库的delete操作。
- PUT : 向服务器发送数据,从而改变信息。类似于数据库的update操作,用来修改内容。
Retrofit使用步骤:
使用Retrofit前 ,需要先引入Retrofit 库。
在Android中添加Retrofit依赖 ,只需要在build.gradle文件中添加以下代码;
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
2.先创建一个包Service类。
定义HTTP的API对应的接口
public interface HttpBinService {
@GET("wenda/comments/{questionId}/json")
Call<ResponseBody> getWendaList(@Path("questionId") String questionId);
}
接口的定义调用服务端URL为wanandroid.com/wenda/comme… 问题id/json需返回定义好对象!
3.加入Okhttp配置
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(1000*80, TimeUnit.SECONDS);//连接超时时间
builder.writeTimeout(1000*80,TimeUnit.SECONDS);//写操作 超时时间
builder.readTimeout(1000*80,TimeUnit.SECONDS);//读操作超时时间
4.加入Retrofit配置
new Retrofit.Builder()
.baseUrl
("https://wanandroid.com/")
//base的网络地址 baseUrl不能为空,且强制要求必需以 / 斜杠结尾
.addConverterFactory(GsonConverterFactory.create())//使用Gson解析
.callbackExecutor(Executors.newSingleThreadExecutor())//使用单独的线程处理 (这很重要,一般网络请求如果不设置可能不会报错,但是如果是下载文件就会报错)
.build();
}
接口实现类对象调用对应的接口:
private void initRequest() throws IOException {
ObjectInputStream.GetField httpBinService = null;
retrofit2.Call<ResponseBody> call = (Call<ResponseBody>) httpBinService.get("lance", "123");
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.i("111111", "onResponse:" + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}
}