Retrofit2 使用
1.導(dǎo)入引用
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
2.初始化請求
* 方法1:
public interface APIService {
@GET("getIpInfo.php")
Call<IP> getIP(@Query("ip") String ip);
}
使用:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://ip.taobao.com/service/")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService apiService = retrofit.create(APIService.class);
Call<IP> call = apiService.getIP("202.202.32.202");
call.enqueue(new Callback<IP>() {
@Override
public void onResponse(Call<IP> call, Response<IP> response) {
IP body = response.body();
String area = body.getData().getArea();
tvRetrofit.setText(area);
}
@Override
public void onFailure(Call<IP> call, Throwable t) {
t.printStackTrace();
}
});
* 方法2:
public class AppStores {
public interface TaobaoIPService {
@GET("getIpInfo.php")
Call<IP> getIP(@Query("ip") String ip);
@FormUrlEncoded
@POST("getIpInfo.php")
Call<IP> postIP(@Field("ip") String ip);
}
static Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://ip.taobao.com/service/")
.addConverterFactory(GsonConverterFactory.create())
.build();
public static AppStores.TaobaoIPService taobaoIPService =
retrofit.create(AppStores.TaobaoIPService.class);
}
建立AppStores請求類,此類只要做一種功能請求(Retrofit是類似與RESTful風格的網(wǎng)絡(luò)請求)。
在此初始化網(wǎng)絡(luò)請求。
3.發(fā)送請求
- retrofit2 發(fā)送請求時不區(qū)分get/post請求,區(qū)分同步/異步請求。
- Call 每個對象實例只能調(diào)用一次,如果想重復(fù)調(diào)用一個接口,可以通過Clone方法來創(chuàng)建一個一模一樣的實例,這個開銷是很小的。
比如說:你可以在每次決定發(fā)請求前 clone 一個之前的實例。(call2 = call.clone();)
- 請求中斷:call.cancel();
同步請求
// 同步請求在主線程中,需要開啟子線程發(fā)送請求。
new Thread(new Runnable() {
@Override
public void run() {
Call<IP> call1 = AppStores.taobaoIPService.getIP("202.202.32.202");
try {
Response<IP> response = call1.execute();
IP ip = response.body();
final String area = ip.getData().getArea();
runOnUiThread(new Runnable() {
@Override
public void run() {
tvRetrofit.setText(area);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
異步請求
Call<IP> call = AppStores.taobaoIPService.postIP("202.202.32.202");
call.enqueue(new Callback<IP>() {
@Override
public void onResponse(Call<IP> call, Response<IP> response) {
IP body = response.body();
String result = body.getData().getCountry();
// 可以直接更改UI,因為onResponse方法已經(jīng)在UI線程中。
tvRetrofit.setText(result);
call.cancel();
}
@Override
public void onFailure(Call<IP> call, Throwable t) {
tvRetrofit.setText(t.toString());
t.printStackTrace();
}
});
4.解析響應(yīng)
參考上面代碼
- 默認使用Gson解析json數(shù)據(jù): addConverterFactory(GsonConverterFactory.create());
- OnResponse響應(yīng)返回:Response<IP> response;
- 在body中獲取解析數(shù)據(jù):IP body = response.body();
- 更新UI在主線程中。異步請求OnResponse是在主線程中的,同步請求是在子線程中進行,所以更新UI應(yīng)該runOnUiThread運行在主線程中。
5.其他知識點
Response
class Response<T> {
okhttp3.Response raw()
int code() // 請求成功 code:200
String message()
Headers headers()
boolean isSuccessful()
T body()
ResponseBody errorBody()
}
通用的請求鏈接
interface GitHubService {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> repoContributors(
@Path("owner") String owner,
@Path("repo") String repo);
// 此種方式,可以傳入Url
@GET
Call<List<Contributor>> repoContributorsPaginate(
@Url String url);
}
Call<List<Contributor>> call =
gitHubService.repoContributors("square", "retrofit");
請求參數(shù)
* @Query(“key”)? -- 用于GET請求查詢參數(shù)
* @QueryMap -- 用于參數(shù)映射
* @Body -- 與@POST注解一起使用,提供查詢主體內(nèi)容
同步請求另外的寫法
private class NetworkCall extends AsyncTask<Call, Void, String> {
@Override
protected String doInBackground(Call… params) {
try {
Call<List<Contributor>> call = params[0];
Response<List<Contributor>> response = call.execute();
return response.body().toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
final TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(result);
}
}
// 點擊
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
final Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");
new NetworkCall().execute(call);
}
});
請求結(jié)果判斷
if (response.isSuccessful() && response.errorBody() == null) {
// 請求成功
Log.d(TAG, "str:" + response.body().toString());
} else {
// 請求失敗
Log.d(TAG, "error code:" + response.code());
Log.d(TAG, "error message:" + response.message());
}
鳴謝
http://ip.taobao.com/service/getIpInfo.php?ip=202.202.32.202
此地址是在網(wǎng)上找到的,感謝_