Android网络请求练习

栏目: 服务器 · 发布时间: 5年前

implementation 'com.lzy.net:okgo:3.0.4'
    implementation 'com.google.code.gson:gson:2.8.5'
复制代码

2.新建 java

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        initOkGo();
    }
    private void initOkGo() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("result");//这里是添加日志拦截,可在logcat中输入result查看请求到的json数据
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);

        builder.readTimeout(10000, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(10000, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(20000, TimeUnit.MILLISECONDS);   //全局的连接超时时间

        // 其他统一的配置
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient,不设置会使用默认的
                .setRetryCount(0);                           
    }
}
复制代码

3.AndroidManifest.xml中添加android:name=".App",添加网络权限

4.MainActivity添加请求简单写法

public class MainActivity extends AppCompatActivity {

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

        OkGo.<LoginBean>post("http://***.do")
                .params("account", "***")
                .params("password", "***")
                .execute(new JsonCallback<LoginBean>() {
                    @Override
                    public void onSuccess(Response<LoginBean> response) {
                        if (response.body().getErrcode() == 0) {
//                          注意这里的toString,想显示全部内容需要重写toString方法
                            Toast.makeText(MainActivity.this, "成功了"+response.body().getData().toString(),
                        } else {
                        }
                    }

                    @Override
                    public void onError(Response<LoginBean> response) {
                        super.onError(response);
                    }
                });

    }

}
复制代码

5.测试接口,复制返回的json数据再用gsonformat生成LoginBean类

6.自定义JsonCallback

public abstract class JsonCallback<T> extends AbsCallback<T> {
    private Type type;
    private Class<T> clz;

    public JsonCallback(Type type) {
        this.type = type;
    }

    public JsonCallback() {
        this.clz = clz;
    }

    @Override
    public T convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null) return null;
        T data = null;
        Gson gson = new Gson();
        JsonReader jsonReader = new JsonReader(body.charStream());
        if (type != null) {
            data = gson.fromJson(jsonReader, type);
        } else if (clz != null) {
            clz = gson.fromJson(jsonReader, clz);
        } else {
            Type genType = getClass().getGenericSuperclass();
            Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            data = gson.fromJson(jsonReader, type);
        }
        return data;
    }
}

复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

自制编程语言 基于C语言

自制编程语言 基于C语言

郑钢 / 人民邮电出版社 / 2018-9-1 / CNY 89.00

本书是一本专门介绍自制编程语言的图书,书中深入浅出地讲述了如何开发一门编程语言,以及运行这门编程语言的虚拟机。本书主要内容包括:脚本语言的功能、词法分析器、类、对象、原生方法、自上而下算符优先、语法分析、语义分析、虚拟机、内建类、垃圾回收、命令行及调试等技术。 本书适合程序员阅读,也适合对编程语言原理感兴趣的计算机从业人员学习。一起来看看 《自制编程语言 基于C语言》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器