Retrofit网络请求入门

来源:互联网 发布:matlab fprintf 矩阵 编辑:程序博客网 时间:2024/05/22 07:40

Retorfit官方介绍
http://square.github.io/retrofit/

1、网络请求的原理

这里写图片描述
在android中所有的网络请求基本上都是相似的

  1. 封装request请求
  2. 在请求队列中执行请求体(网络框架就是在这里封装,比如可以使用httpurlconnection,httpclient,okhttp)
  3. 执行http请求
  4. 返回成功或者失败的回调

2、Retrofit的介绍

强调种是一种类型安全的网络请求
Aype-safe HTTP client for Android and Java
这里写图片描述
Retrofit是通过泛型保证类型安全的

Retorfit通过注解的方法配置http请求,因此如果我们改换比如okhttp换成httpclient或者httpurlconnection是不需要改动上层代码的。

3、Retrofit的使用步骤

这里写图片描述 这里写图片描述
Retrofit的使用就是以下几步:
代码中借用的ulr地址
第一个直接通过url获取数据
http://www.weather.com.cn/data/cityinfo/101010100.html
第二个通过url中id查询
http://wthrcdn.etouch.cn/weather_mini?city=北京
1、添加依赖

compile 'com.squareup.retrofit2:retrofit:2.0.1'compile 'com.squareup.retrofit2:converter-gson:2.0.1'

2、定义接口,参数声明,Url都通过Annotation指定 Annotation写
在接口内方法上

  Retrofit retrofit=new Retrofit.Builder()                        .baseUrl("http://www.weather.com.cn")                        .addConverterFactory(GsonConverterFactory.create())                        .build();

接口代码

public interface ApiService {    //http://www.weather.com.cn/data/cityinfo/101010100.html    @GET("data/cityinfo/{address}.html")    Call<Weather> getInfo(@Path("address")String address);}

2、通过Retrofit生成一个接口的实现类(动态代理)

  ApiService apiService=retrofit.create(ApiService.class);

3、发送请求,回调

  Call<Weather> call=apiService.getInfo("101010100");                call.enqueue(new Callback<Weather>() {                    @Override                    public void onResponse(Call<Weather> call, Response<Weather> response) {                        Weather weather=response.body();                        tv_text.setText("地区:  "+weather.weatherinfo.city+"  天气:   "+weather.weatherinfo.weather);                    }                    @Override                    public void onFailure(Call<Weather> call, Throwable t) {                    }                });

4、Retrofit代码追踪

1、通过new retorfit类用build模式返回retorfit对象

这里写图片描述

2、用retorift 创建一个动态代理,最终返回一个okHttpCall

这里写图片描述

3、发送一个call请求(同步或者异步 )

这里写图片描述

4、demo代码如下

activity中

package com.example.yu.retrofit;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView;import api.ApiService;import bean.Weather;import bean.WeatherQuery;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private Button btn_request;    private Button btn_query;    private TextView tv_text;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btn_request= (Button) findViewById(R.id.btn_request);        btn_query= (Button) findViewById(R.id.btn_query);        tv_text= (TextView) findViewById(R.id.tv_text);        btn_query.setOnClickListener(this);        btn_request.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.btn_request:                Retrofit retrofit=new Retrofit.Builder()                        .baseUrl("http://www.weather.com.cn")                        .addConverterFactory(GsonConverterFactory.create())                        .build();                ApiService apiService=retrofit.create(ApiService.class);                Call<Weather> call=apiService.getInfo("101010100");                call.enqueue(new Callback<Weather>() {                    @Override                    public void onResponse(Call<Weather> call, Response<Weather> response) {                        Weather weather=response.body();                        tv_text.setText("地区:  "+weather.weatherinfo.city+"  天气:   "+weather.weatherinfo.weather);                    }                    @Override                    public void onFailure(Call<Weather> call, Throwable t) {                    }                });                break;            case  R.id.btn_query:                Retrofit retrofit_query=new Retrofit                        .Builder()                        .baseUrl("http://wthrcdn.etouch.cn/")                        .addConverterFactory(GsonConverterFactory.create())                        .build();                ApiService apiService2=retrofit_query.create(ApiService.class);                Call<WeatherQuery> call2 =apiService2.getQueryInfo("北京");                call2.enqueue(new Callback<WeatherQuery>() {                    @Override                    public void onResponse(Call<WeatherQuery> call, Response<WeatherQuery> response) {                        WeatherQuery weatherQuery=response.body();                        tv_text.setText("    地区    "+weatherQuery.data.city+"\n"                                +"    温度   "+weatherQuery.data.wendu+"\n"                                +"    感冒   "+weatherQuery.data.ganmao);                    }                    @Override                    public void onFailure(Call<WeatherQuery> call, Throwable t) {                    }                });                break;        }    }}

配置接口类

package api;import bean.Weather;import bean.WeatherQuery;import retrofit2.Call;import retrofit2.http.GET;import retrofit2.http.Path;import retrofit2.http.Query;/** * Created by yu on 2016/6/22. */public interface ApiService {    //http://www.weather.com.cn/data/cityinfo/101010100.html    @GET("data/cityinfo/{address}.html")    Call<Weather> getInfo(@Path("address")String address);    //http://wthrcdn.etouch.cn/weather_mini?city=北京    @GET("weather_mini")    Call<WeatherQuery> getQueryInfo(@Query("city") String city);}

代码下载地址
http://download.csdn.net/detail/androidxiaogang/9556589

2 0