接口
package com.example.retrofit.connector; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; /** * date:2017/5/21 * author:易宸锋(dell) * function: */ public interface MyServerInterface { /// // GET网络请求方式 /// /**Get请求,方法中无参数 * 作用:GET请求最简单的写法,无Path参数和Query参数 * article/list/latest?page=%d实际是Constant下的URL_LATEST地址 * @GET()里的东西是要拼接的网址,注意直接把page=1了 */ @GET("article/list/latest?page=1") Call<ResponseBody> getLatestJsonString(); }
接口
package com.example.retrofit.net; /** * 项目糗事百科的网址 */ public class Constant { //baseurl public final static String URL_BASE = "http://m2.qiushibaike.com/"; }
主页面
package com.example.retrofit; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import com.example.retrofit.connector.MyServerInterface; import com.example.retrofit.net.Constant; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; //Retrofit之基本使用,get请求无参数模式,注意添加网络权限 public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private TextView textView_info; private Call<ResponseBody> mCall; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控件 textView_info = (TextView) findViewById(R.id.textView_info); //初始化Retrofit initRetrofit(); } private MyServerInterface serverInterface = null; private void initRetrofit() { //创建 retrofit 对象 /*Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://m2.qiushibaike.com/") .build();*/ Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.URL_BASE) .build(); //创建接口对象,参数:接口的字节码 serverInterface = retrofit.create(MyServerInterface.class); //类似okhttp,通过接口对象,调用抽象方法,创建出call对象 mCall = serverInterface.getLatestJsonString(); mCall.enqueue(new Callback<ResponseBody>() { //请求成功的回调(Retrofit与okhttp不同,回调方法是运行在主线程而不是子线程的) @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { //打一个log Log.d(TAG, "---->threadId:" + Thread.currentThread().getId()); //对返回结果做成功与内容的判断 if (response.isSuccess() && response.body() != null) { try { //得到结果 String result = response.body().string(); //更新UI textView_info.setText(result); } catch (IOException e) { e.printStackTrace(); } } } //请求失败的回调 @Override public void onFailure(Call<ResponseBody> call, Throwable t) {} }); } //为节约资源,当屏幕不可见时,我们停止网络请求 @Override protected void onStop() { super.onStop(); if (mCall != null) { mCall.cancel(); } } }
//Retrofit2的依赖 compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
布局默认的就行,不要忘了加id