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

复制代码

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

查看所有标签

猜你喜欢:

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

Just My Type

Just My Type

Simon Garfield / Profile Books / 2010-10-21 / GBP 14.99

What's your type? Suddenly everyone's obsessed with fonts. Whether you're enraged by Ikea's Verdanagate, want to know what the Beach Boys have in common with easy Jet or why it's okay to like Comic Sa......一起来看看 《Just My Type》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具