Retorfit2 学习笔记1

1.先添加依赖

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

2.无参异步请求 返回默认响应体json

Retrofit retrofit = new Retrofit.Builder()
     .baseUrl("http://gank.io/")        
     .addConverterFactory(GsonConverterFactory.create())
     .build();
GnakApi api = retrofit.create(GnakApi.class);
Call<ResponseBody> call = api.getAndroidInfo();
//execute()是同步 这里是异步
call.enqueue(new Callback<ResponseBody(){
    @Override
public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
           try {      
                textView.setText(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
}

  @Override
public void onFailure(Call<ResponseBody>call,Throwable t){
         t.printStackTrace();
     }
});

3 .同步–请求可能是导致APP在4.0及以上版本崩溃的原因

同步方法被执行在主线程,这意味着UI线程将会被阻塞在请求执行的时间段内,可能会导致APP在4.0及以上版本崩溃。
同步方法提供了直接实时返回值的能力,因为这个操作在进行网络请求时会阻塞一切,为了不阻塞UI, 你得先开启子线程去请求

 new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://gank.io/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
                    GnakApi api = retrofit.create(GnakApi.class);
                    Call<ResponseBody> call = api.getAndroidInfo();
                    ResponseBody response =call.execute().body();
                    textView.setText(response.string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

下面贴上接口

public interface GnakApi {
    @GET("api/data/Android/10/1")
    Call<ResponseBody> getAndroidInfo();
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值