1. 程式人生 > >Retrofit網路請求入門

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的使用步驟

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);
}