Retrofit学习

---恢复内容开始---

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            ImageView view = (ImageView) findViewById(R.id.image);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://www.baidu.com/?tn=62095104_19_oem_dg")
                .build();
        BlogService service = retrofit.create(BlogService.class);

        Call<ResponseBody> call = service.getBlog(2);
//用法和OkHttp的call如出一辙,不同的是,Android系统中回调方法执行在主线程
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    System.out.println(response.body().string());
                    System.out.println(response.code() + "  " + response.isSuccessful());//200  true
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }
    public interface BlogService {
        @GET("blog/{id}")/*这里的{id} 表示是一个变量*/
        Call<ResponseBody> getBlog(@Path("id") int id);
    }
    }

 

retrofit框架是对OKhttp的包装,为了简化代码逻辑和代码调用,不同于Volley,retrofit更偏向大型持久的数据连接,类似于httpurlconnection.retrofit使用注解的方式调用方法,内置了很多注解,比如@get表示使用get请求,可以看看这个链接的分享https://blog.csdn.net/qiang_xi/article/details/53959437    

 

<uses-permission android:name="android.permission.INTERNET" />
还有依赖:
implementation 'com.squareup.okhttp3:okhttp:4.0.0-RC1'
implementation 'com.squareup.okio:okio:2.2.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'


 

---恢复内容结束---

转载于:https://www.cnblogs.com/Ocean123123/p/10997847.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值