retrofit框架

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sliverbullets/article/details/80394493

模式:观察者模式
导包

  //retrofit 包
 implementation 'com.squareup.retrofit2:retrofit:2.0.2'
  //gson 包 解析用到.addConverterFactory(GsonConverterFactory.create())
 implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

使用:

>package com.example.retrofitdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    /**
     * 1. 导包
     * 2. 创建接受接口 用注解方式写明请求方式:get("url后面部分或者其他") post("/form")
     * 3. 创建实体类
     * 4. 创建Retrofit实例通过build方法
     * 5. 实例化request
     * 6. call.enqueue(new Callback<类>{....})开始网络请求
     * 7. 在onResponse方法中获取数据基本与okhttp就一样了
     * */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        request();
    }

    public void request(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://fy.iciba.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        GetRequestInterface request = retrofit.create(GetRequestInterface.class);

        Call<Translation> call = request.getCall();
        call.enqueue(new Callback<Translation>( ) {
            @Override
            public void onResponse(Call<Translation> call, Response<Translation> response) {
                response.body().show();

            }

            @Override
            public void onFailure(Call<Translation> call, Throwable t) {

            }
        });

    }
}

接口类

package com.example.retrofitdemo;

import retrofit2.Call;
import retrofit2.http.GET;

public interface GetRequestInterface {

    @GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")
    Call<Translation> getCall();

}

Bean数据类

>public class Translation {
    private int status;

    private content content;

    private static class content{
        private String from;
        private String to;
        private String vendor;
        private String out;
        private int errNo;
    }

    //定义 输出返回数据 的方法
    public void show() {
        System.out.println(status);

        System.out.println(content.from);
        System.out.println(content.to);
        System.out.println(content.vendor);
        System.out.println(content.out);
        System.out.println(content.errNo);
    }
}

猜你喜欢

转载自blog.csdn.net/sliverbullets/article/details/80394493
今日推荐