Retrofit 是什麼呢?Rotrofit是square開發的一個jar,便于用戶端與伺服器的資料互動。下面通過一個簡單的例子,給大家起到一個抛磚引玉的作用.
1 在Android Studio中引入Retrofit2
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
記得要在AndroidManifest中添加Intent 權限.
2 定義一個Bean,使用Gson完成請求資料與POJO的轉換
package com.example.mvgos.retrofit2demo;
public class RepositoryBean {
String full_name;
String html_url;
int contributions;
@Override
public String toString() {
return full_name + " (" + contributions + ")";
}
}
3 定一個Interface,完成Retrofit初始化和封裝網絡請求涉及的接口
package com.example.mvgos.retrofit2demo;
import java.util.List;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface GitHubService {
@GET("orgs/{orgName}/repos")
Call<List<RepositoryBean>> queryOrgRepos(
@Path("orgName") String orgName);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
4調用接口完成網絡請求
//同步調用,Android中不允許在Main Thread中進行網絡請求,這裡使用下面的一步請求
public List<RepositoryBean> getContributorList() throws Exception{
GitHubService gitHubService = retrofit.create(GitHubService.class);
Call<List<RepositoryBean>> call = gitHubService.queryOrgRepos("guchuanhangOrganization");
List<RepositoryBean> result = call.execute().body();
return result;
}
//異步請求
public void getContributorListA() throws Exception {
GitHubService gitHubService = retrofit.create(GitHubService.class);
Call<List<RepositoryBean>> call = gitHubService.queryOrgRepos("guchuanhangOrganization");
call.enqueue(new Callback<List<RepositoryBean>>() {
@Override
public void onResponse(Call<List<RepositoryBean>> call, Response<List<RepositoryBean>> response) {
List<RepositoryBean> conList=response.body();
}
@Override
public void onFailure(Call<List<RepositoryBean>> call, Throwable t) {
textView.setText(t.getLocalizedMessage());
}
});
}
5 綜合測試
<?xml version="1.0" encoding="utf-8"?>
<!--activity_main.xml-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.mvgos.retrofit2demo.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fetch"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="151dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="@+id/textView"
android:layout_above="@+id/button"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:textIsSelectable="false" />
</RelativeLayout>
//MainActivity.java
package com.example.mvgos.retrofit2demo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.example.mvgos.retrofit2demo.GitHubService.retrofit;
public class MainActivity extends AppCompatActivity {
public List<RepositoryBean> getContributorList() throws Exception{
GitHubService gitHubService = retrofit.create(GitHubService.class);
Call<List<RepositoryBean>> call = gitHubService.queryOrgRepos("guchuanhangOrganization");
List<RepositoryBean> result = call.execute().body();
return result;
}
public void getContributorListA() throws Exception {
GitHubService gitHubService = retrofit.create(GitHubService.class);
Call<List<RepositoryBean>> call = gitHubService.queryOrgRepos("guchuanhangOrganization");
call.enqueue(new Callback<List<RepositoryBean>>() {
@Override
public void onResponse(Call<List<RepositoryBean>> call, Response<List<RepositoryBean>> response) {
List<RepositoryBean> conList=response.body();
// Type conListType=new TypeToken<List<Contributor>>(){}.getType();
// Gson gson=new Gson();
// String resultString= gson.toJson(conList,conListType);
RepositoryBean[] myArray = conList.toArray(new RepositoryBean[]);
textView.setText(Arrays.toString(myArray));
}
@Override
public void onFailure(Call<List<RepositoryBean>> call, Throwable t) {
textView.setText(t.getLocalizedMessage());
}
});
}
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView = (TextView) findViewById(R.id.textView);
try{
getContributorListA();
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
苦于找不到伺服器接口進行測試的同學請參考 github api.
參考位址:https://zeroturnaround.com/rebellabs/getting-started-with-retrofit-2/