okhttp-utils用法总结

2017-02-08  本文已影响3557人  yangpanRoy

对okhttp的封装类,okhttp见:https://github.com/square/okhttp.
目前对应okhttp版本3.3.1.
okhttp-utils Github:https://github.com/hongyangAndroid/okhttputils

引用方法

    compile 'com.zhy:okhttputils:2.6.2'

下载最新jar:okhttputils-2_6_2.jar
注:需要同时导入okhttp和okio的jar,下载见:https://github.com/square/okhttp.

用法示例

json-server内容

{
  "user": {
    "username": "Roy",
    "password": "123"
  },
  "users": [
    {
      "password": "123",
      "username": "Roy",
      "id": 1
    },
    {
      "password": "12345",
      "username": "Tom",
      "id": 2
    },
    {
      "password": "54321",
      "username": "Jack",
      "id": 3
    }
  ]
}

User类

public class User {

    public String username ; 
    public String password  ;
    
    public User() {
        // TODO Auto-generated constructor stub
    }
    
    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

    @Override
    public String toString()
    {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

GET请求

适用于string对象

String url = "http://192.168.191.1:3000/" + "user"; //url设置成自己的json-server地址
OkHttpUtils
    .get()
    .url(url)
    .build()
    .execute(new StringCallback() //使用StringCallback回调String类型数据
            {
                @Override
                public void onError(Request request, Exception e)
                {

                }

                @Override
                public void onResponse(String response)
                {
                    //解析出的response为String类型,可以进一步处理
                }
            });

适用于JavaBean对象

public void getUser(View view)
    {
        String url = "http://192.168.191.1:3000/" + "user"; //url设置成自己的json-server地址
        OkHttpUtils
                .get()//
                .url(url)//
                .build()//
                .execute(new UserCallback() { //使用UserCallback回调User类的对象,可自己定义JavaBean对象
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mTv.setText("onError:" + e.getMessage());
                        //mTv为TextView打印Error信息
                    }

                    @Override
                    public void onResponse(User response, int id) {
                        mTv.setText("onResponse:" + response.getPassword());
                        //mTv为TextView打印response信息
                        //解析出的response为User类对象,此处使用response.getPassword()来获取password属性
                    }
                });
    }
UserCallback
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;

import okhttp3.Response;

public abstract class UserCallback extends Callback<User>
{
    @Override
    public User parseNetworkResponse(Response response, int id) throws IOException
    {
        String string = response.body().string();
        User user = new Gson().fromJson(string, User.class);
        return user;
    }
}

适用于List<Bean>对象

public void getUsers(View view)
    {
        String url = "http://192.168.191.1:3000/" + "users"; //url设置成自己的json-server地址
        OkHttpUtils//
                .get()//
                .url(url)//
                .build()//
                .execute(new ListUserCallback() //使用ListUserCallback回调List<Bean>数组,可自己定义JavaBean对象
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        mTv.setText("onError:" + e.getMessage());
                        //mTv为TextView打印Error信息
                    }

                    @Override
                    public void onResponse(List<User> response, int id)
                    {
                        mTv.setText("onResponse:" + response.get(2).toString());
                        //mTv为TextView打印response信息
                        //解析出的response为List<User>数组,此处使用response.get(2).toString()来获取数组中第3个User对象,并用toString方法输出
                    }
                });
    }
ListUserCallback
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;
import java.util.List;

import okhttp3.Response;

public abstract class ListUserCallback extends Callback<List<User>>
{

    @Override
    public List<User> parseNetworkResponse(Response response,int id) throws IOException
    {
        String string = response.body().string();
        List<User> users = new Gson().fromJson(string, new TypeToken<List<User>>(){}.getType());
        return users;
    }


}

POST请求

适用于json字符串

public void postString(View view)
    {
        String url = "http://192.168.191.1:3000/" + "users"; //url设置成自己的json-server地址
        OkHttpUtils
                .postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8")) //设置post的字符串为json字符串并设置编码
                .content(new Gson().toJson(new User("zhy", "123"))) //用Gson将User对象转化为Json字符串的形式作为content
                .build()
                .execute(new MyStringCallback());
    }
MyStringCallback
package Callback;

import android.util.Log;

import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

public class MyStringCallback extends StringCallback
{
    //MyStringCallback用于向json server处理有关字符串的请求(Json/Http/Https 字符串callback)

    @Override
    public void onError(Call call, Exception e, int id)
    {
        e.printStackTrace();
    }

    @Override
    public void onResponse(String response, int id)
    {
        Log.i("Tag", "MyStringCallback success");

        switch (id)
        {
            case 100:
                Log.i("http", "http callback success");
                break;
            case 101:
                Log.i("https", "https callback success");
                break;
        }
    }
}

适用于JavaBean对象

public void postUser(View view)
    {
        String url = "http://192.168.191.1:3000/" + "user"; //url设置成自己的json-server地址
        OkHttpUtils
                .post()//
                .url(url)//
                .addParams("username", "Roy")//设置Post参数
                .addParams("password", "123")//设置Post参数
                .build()//
                .execute(new UserCallback() { //使用UserCallback回调User类的对象,可自己定义JavaBean对象,UserCallback内容同上
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mTv.setText("onError:" + e.getMessage());
                        //mTv为TextView打印Error信息
                    }

                    @Override
                    public void onResponse(User response, int id) {
                        mTv.setText("onResponse:" + response.getPassword());
                        //mTv为TextView打印response信息,response为刚刚POST的User类对象
                        //解析出的response为User类对象,此处使用response.getPassword()来获取password属性
                    }
                });
    }

待续

上一篇下一篇

猜你喜欢

热点阅读