1.Ctrl+Alt+Shift+S 打开ProjectStructure ->app->Dependencies 添加:
compile 'com.squareup.retrofit2:retrofit:2.2.0' compile 'com.squareup.retrofit2:converter-gson:2.2.0'2.添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>3.修改activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.rokkki.retrofit_2.MainActivity"> <TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="hello"/> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="button"/> </LinearLayout>4.添加Book.java类: API地址: https://api.douban.com/v2/book/search?q=金瓶梅&tag=&start=0&count=1 同样用GsonFormat方式,之后手动添加toString函数
5.Service.java:
public interface Service { @GET("book/search") Call<Book> getBook(@Query("q") String name, @Query("tag") String tag, @Query("start") int start, @Query("count") int count); }6.修改MainActivity.java:
public class MainActivity extends AppCompatActivity { private TextView textView; private Button button; public static final String API_URL="https://api.douban.com/v2/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.text_view); button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); Service service = retrofit.create(Service.class); Call<Book> call = service.getBook("金瓶梅",null,0,1); call.enqueue(new Callback<Book>() { @Override public void onResponse(Call<Book> call, Response<Book> response) { textView.setText(response.body().toString()); } @Override public void onFailure(Call<Book> call, Throwable t) { t.printStackTrace(); } }); } }); } }