Retrofit异步请求数据 (两种接口路径 ?,/)

    1依赖:

compile 'org.greenrobot:greendao:3.2.2'
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.google.code.gson:gson:2.2.4'
    2权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
3.主布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.retrofitdemo0413.MainActivity">

    <TextView
        android:id="@+id/text_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!"/>
    <Button
        android:id="@+id/btn_dianji"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Retrofit?路径请求数据"/>
    <Button
        android:id="@+id/btn_dianji2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Retrofit/路径请求数据"/>

</LinearLayout>

4.定义接口

package com.example.retrofitdemo0413;

import java.util.List;
import java.util.Map;
import retrofit2.http.GET;
import retrofit2.Call;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;

//1.声明一个接口
    public interface ApiService {
        //2.声明一个接口对象 路径""
    @GET("user/getUserInfo")
    Call<MessageBean<InfoBean>> getInfo(@QueryMap Map<String,String> params);

    //3.声明一个借口对象 路径“/”
    @GET("search/query/listview/category/Android/count/{count}/page/{page}")
    Call<NewsBean<List<News>>> getNews(@Path("count") String count,@Path("page") String page);
}
5.Acivity的实现

package com.example.retrofitdemo0413;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.text_show)
    TextView textShow;
    @BindView(R.id.btn_dianji)
    Button btn_dj;
    @BindView(R.id.btn_dianji2)
    Button btn_Dianji2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }
    
    //点击事件
    @OnClick({R.id.btn_dianji, R.id.btn_dianji2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_dianji:

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("https://www.zhaoapi.cn/user/")
                        //添加Gson自动解析
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                ApiService service = retrofit.create(ApiService.class);

                Map<String, String> params = new HashMap<>();
                params.put("uid", "71");
                Call<MessageBean<InfoBean>> call = service.getInfo(params);

                //进行异步操作
                call.enqueue(new Callback<MessageBean<InfoBean>>() {
                    //成功
                    @Override
                    public void onResponse(Call<MessageBean<InfoBean>> call, Response<MessageBean<InfoBean>> response) {
                        Log.e("======+", response.body().getMsg());
                        Log.e("线程名称", Thread.currentThread().getId() + Thread.currentThread().getName());
                        textShow.setText("晚安");
                    }

                    //失败
                    @Override
                    public void onFailure(Call<MessageBean<InfoBean>> call, Throwable t) {
                        Log.e("-----", t.getMessage());
                    }
                });
                break;
            case R.id.btn_dianji2:

                Retrofit retrofit2 = new Retrofit.Builder()
                        .baseUrl("http://gank.io/api/")
                        //添加Gson自动解析
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                 ApiService service2 = retrofit2.create(ApiService.class);
                Call<NewsBean<List<News>>> call1 = service2.getNews("10","1");
                call1.enqueue(new Callback<NewsBean<List<News>>>() {
                    @Override
                    public void onResponse(Call<NewsBean<List<News>>> call, Response<NewsBean<List<News>>> response) {
                        List<News> results = response.body().getResults();
                        if(results!=null){
                            Log.i("新闻条目的数量:", String.valueOf(results.size()));
                        }else{
                            Log.i("新闻条目的数量:","0");
                        }
                    }

                    @Override
                    public void onFailure(Call<NewsBean<List<News>>> call, Throwable t) {
                        Log.i("++++", t.getMessage());

                    }
                });
                break;
        }
    }
}
6.第一条接口的外层泛型封装类

package com.example.retrofitdemo0413;

public class MessageBean<T> {

    private String msg;
    private String code;
    private T data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    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;
    }
}
7.第一条接口的内层封装类

package com.example.retrofitdemo0413;

public class InfoBean {

    private String appsecret;
    private String createtime;
    private int fans;
    private int follow;
    private int gender;
    private String icon;
    private String mobile;
    private int money;
    private String nickname;
    private String password;
    private String token;
    private int uid;
    private String username;

    public String getAppsecret() {
        return appsecret;
    }

    public void setAppsecret(String appsecret) {
        this.appsecret = appsecret;
    }

    public String getCreatetime() {
        return createtime;
    }

    public void setCreatetime(String createtime) {
        this.createtime = createtime;
    }

    public int getFans() {
        return fans;
    }

    public void setFans(int fans) {
        this.fans = fans;
    }

    public int getFollow() {
        return follow;
    }

    public void setFollow(int follow) {
        this.follow = follow;
    }

    public int getGender() {
        return gender;
    }

    public void setGender(int gender) {
        this.gender = gender;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
8.第二条接口的外层泛型封装类

package com.example.retrofitdemo0413;

public class NewsBean<T> {
    private String count;
    private Boolean error;
    private T results;

    public String getCount() {
        return count;
    }

    public void setCount(String count) {
        this.count = count;
    }

    public Boolean getError() {
        return error;
    }

    public void setError(Boolean error) {
        this.error = error;
    }

    public T getResults() {
        return results;
    }

  9.第二条接口的内层封装类  
package com.example.retrofitdemo0413;

public class News {

    private String desc;
    private String ganhuo_id;
    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 getGanhuo_id() {
        return ganhuo_id;
    }

    public void setGanhuo_id(String ganhuo_id) {
        this.ganhuo_id = ganhuo_id;
    }

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


阅读更多
想对作者说点什么?
相关热词

博主推荐

换一批

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