Rretrofit2 使用

Retrofit2 使用

1.导入引用

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 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 call = apiService.getIP("202.202.32.202");
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                IP body = response.body();
                String area = body.getData().getArea();
                tvRetrofit.setText(area);
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                t.printStackTrace();
            }
        });

* 方法2:

    public class AppStores {
        public interface TaobaoIPService {
            @GET("getIpInfo.php")
            Call getIP(@Query("ip") String ip);
    
            @FormUrlEncoded
            @POST("getIpInfo.php")
            Call 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风格的网络请求)。
在此初始化网络请求。

3.发送请求

- retrofit2 发送请求时不区分get/post请求,区分同步/异步请求。
- Call 每个对象实例只能调用一次,如果想重复调用一个接口,可以通过Clone方法来创建一个一模一样的实例,这个开销是很小的。
  比如说:你可以在每次决定发请求前 clone 一个之前的实例。(call2 = call.clone();)
- 请求中断:call.cancel();

同步请求

    // 同步请求在主线程中,需要开启子线程发送请求。
    new Thread(new Runnable() {
        @Override
        public void run() {
            Call call1 = AppStores.taobaoIPService.getIP("202.202.32.202");
            try {
                Response 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 call = AppStores.taobaoIPService.postIP("202.202.32.202");
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            IP body = response.body();
            String result = body.getData().getCountry();
            // 可以直接更改UI,因为onResponse方法已经在UI线程中。
            tvRetrofit.setText(result);

            call.cancel();
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            tvRetrofit.setText(t.toString());
            t.printStackTrace();
        }
    });

4.解析响应

参考上面代码

- 默认使用Gson解析json数据: addConverterFactory(GsonConverterFactory.create());
- OnResponse响应返回:Response response;
- 在body中获取解析数据:IP body = response.body();
- 更新UI在主线程中。异步请求OnResponse是在主线程中的,同步请求是在子线程中进行,所以更新UI应该runOnUiThread运行在主线程中。

5.其他知识点

Response

    class Response {
      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> repoContributors(
        @Path("owner") String owner,
        @Path("repo") String repo);

      // 此种方式,可以传入Url
      @GET
      Call> repoContributorsPaginate(
          @Url String url);
    }

    Call> call = 
        gitHubService.repoContributors("square", "retrofit");

请求参数

    * @Query(“key”)  -- 用于GET请求查询参数
    * @QueryMap -- 用于参数映射
    * @Body -- 与@POST注解一起使用,提供查询主体内容

同步请求另外的写法

    private class NetworkCall extends AsyncTask {
      @Override
      protected String doInBackground(Call… params) {
        try {
          Call> call = params[0];
          Response> 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> call = gitHubService.repoContributors("square", "retrofit");
        new NetworkCall().execute(call);
      }
    });

请求结果判断

    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
此地址是在网上找到的,感谢_

你可能感兴趣的:(Rretrofit2 使用)