Retrofit简单使用

//Bean类
package com.bwie.httpdemo;

import com.google.gson.annotations.SerializedName;

/**
 * Created by eric on 2018/4/13.
 */

public class MessageBean<T> {
    @SerializedName("msg")
    private String message;
    private String code;
    private T data;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

//集合数据  我这是分开写的      根据个人的习惯
package com.bwie.httpdemo;

import com.google.gson.annotations.SerializedName;

/**
 * Created by eric on 2018/4/13.
 */

public class News {

    /**
     * desc : 还在用ListView?
     * ganhuo_id : 57334c9d67765903fb61c418
     * publishedAt : 2016-05-12T12:04:43.857000
     * readability :
     * type : Android
     * url : http://www.jianshu.com/p/a92955be0a3e
     * who : 陈宇明
     */

    private String desc;
    @SerializedName("ganhuo_id")
    private String ganhuoId;
    private String publishedAt;
    private String readability;
    private String type;
    private String url;
    private String who;

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getGanhuoId() {
        return ganhuoId;
    }

    public void setGanhuoId(String ganhuoId) {
        this.ganhuoId = ganhuoId;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(String publishedAt) {
        this.publishedAt = publishedAt;
    }

    public String getReadability() {
        return readability;
    }

    public void setReadability(String readability) {
        this.readability = readability;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getWho() {
        return who;
    }

    public void setWho(String who) {
        this.who = who;
    }
}

//ApiService
package com.bwie.httpdemo;

import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;

/**
 * Created by eric on 2018/4/13.
 */

public interface ApiService {
    @GET("user/getUserInfo")
    Call<MessageBean<LoginInfo>> getInfo(@Query("uid") String id);

    @GET("search/query/listview/category/Android/count/{count}/page/{page}")
    Call<MessageData<List<News>>> getNews(@Path("count") String count, @Path("page") String page);

    @POST("")
    @Headers({"source:android"})
    Call<String> callPost(@Header("source") String header);
}


//Mainactivity
package com.bwie.httpdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class RetrofitActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "RetrofitActivity";
    private TextView txtShow;
    private Button btnRequest;
    private Button btnRequestGank;

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

        txtShow = findViewById(R.id.txt_show);
        btnRequest = findViewById(R.id.btn_request);
        btnRequestGank = findViewById(R.id.btn_request_gank);

        btnRequest.setOnClickListener(this);
        btnRequestGank.setOnClickListener(this);

        Log.i(TAG, "主线程: " + Thread.currentThread().getId() + "---" + Thread.currentThread().getName());

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_request:
                requestNormal();
                break;
            case R.id.btn_request_gank:
                requestGank();
                break;
        }
    }

    /**
     * 请求干货的接口
     */
    private void requestGank() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://gank.io/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

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

        Call<MessageData<List<News>>> call = service.getNews("10", "1");
        call.enqueue(new Callback<MessageData<List<News>>>() {
            @Override
            public void onResponse(Call<MessageData<List<News>>> call, Response<MessageData<List<News>>> response) {
                List<News> results = response.body().getResults();
                if (results != null) {
                    Log.i(TAG, "获取的新闻条目数量是: " + results.size());
                } else {
                    Log.i(TAG, "获取的新闻条目数量是: 0");
                }
            }

            @Override
            public void onFailure(Call<MessageData<List<News>>> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getMessage());
            }
        });

    }

    // 普通的网络请求
    private void requestNormal() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://www.zhaoapi.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

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

//        Map<String, String> params = new HashMap<>();
//        params.put("uid", "71");
//        Call<MessageBean<LoginInfo>> call = service.getInfo(params);
        Call<MessageBean<LoginInfo>> call = service.getInfo("71");
        call.enqueue(new Callback<MessageBean<LoginInfo>>() {
            @Override
            public void onResponse(Call<MessageBean<LoginInfo>> call, Response<MessageBean<LoginInfo>> response) {
                // 和okhttp不一样的是,回调已经是在主线程了,不需要手动切换了
                Log.i(TAG, "retrofit回调线程: " + Thread.currentThread().getId() + "---" + Thread.currentThread().getName());
                Log.i(TAG, "onResponse: " + response.body().getMessage());
                txtShow.setText("网络请求成功");
            }

            @Override
            public void onFailure(Call<MessageBean<LoginInfo>> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getMessage());
            }
        });
    }
}
阅读更多
想对作者说点什么?
相关热词

博主推荐

换一批

没有更多推荐了,返回首页