Retrofit笔记->结合Rxjava初识

本文介绍了如何在项目中添加Retrofit依赖和网络权限,展示了Retrofit的同步和异步调用方式,并通过接口申明说明了可能出现的NetworkOnMainThreadException错误。
摘要由CSDN通过智能技术生成

添加依赖:

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3'

添加网络权限:

<uses-permission android:name="android.permission.INTERNET"/>


同步调用Demo

//创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://115.215.206.23:8880")
        .build();

//创建调用API请求
 LogApi logApi = retrofit.create(LogApi.class);
Call<ResponseBody> call = logApi.getCode("log","18799155201","123456");

try {
    Response<ResponseBody> bodyResponse = call.execute();
    String body = bodyResponse.body().string();//获取返回体的字符串
    Log.i("snow",body);
} catch (IOException e) {
    e.printStackTrace();
}

接口申明如下:

public interface LogApi {
    @GET("/getLogCode.action?")
    Call<LogInfo> getCode(@Query("reqType") String reqType,@Query("userId") String userId,@Query("passWord") String passWord);
}

注意:会提示NetworkOnMainThreadException,原因你懂的。


异步调用Demo


Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://114.215.204.23:8880")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

LogApi logApi = retrofit.create(LogApi.class);
Call<LogInfo> call = logApi.getCode("log","18799155201","123456");


call.enqueue(new Callback<LogInfo>() {
    @Override
    public void onResponse(Call<LogInfo> call, Response<LogInfo> response) {

            Log.i("snow", "response=" + response.body().getMsg());

    }

    @Override
    public void onFailure(Call<LogInfo> call, Throwable t) {
        Log.i("snow", "onFailure=" + t.getMessage());
    }
});


注解 描述
@Path variable substitution for the API endpoint (i.e. username will be swapped for {username} in the URL endpoint).
@Query specifies the query key name with the value corresponding to the value of that annotated parameter.
@Body payload for the POST call




























































































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值