记录Retrofit的post,get用法。

下面是方法,里面都有注释:

public interface GitHubClient {

    @FormUrlEncoded     //这个是post请求必须要加的注解
    @POST("topic/getAllShareGoodTopics")    //代表BaseUrl和这里面的拼接后的完整地址
    Call<ResponseBody> getUserString(
            @Field("shareGoodInfoId") String shareGoodInfoId, //添加的参数,必须使用@Field注解
            @Field("token") String token        //添加的参数
    );


    @GET("/topic/{id}/{token}")     //id  和token是可以传入的参数
    Call<ResponseBody> getUserInfo(
            @Path("id") int id ,
            @Path("token") String token
    );
    
}


然后就是调用了,下面是代码:

private void getData() {
        String BASE_URL = "http://api.github.com/";	//自己的url前缀

        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(100, TimeUnit.SECONDS)
                .readTimeout(100,TimeUnit.SECONDS)
                .connectTimeout(100,TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
               .client(okHttpClient)
               .baseUrl(BASE_URL)
               .addConverterFactory(GsonConverterFactory.create())  //这个是Gson解析的,觉得没什么必要,还是在onResponse回调里面自己解析比较好
               .build();

        GitHubClient gitHubClient = retrofit.create(GitHubClient.class);

        //这里就是调用了post方法。
        Call<ResponseBody> call = gitHubClient.getUserString("1088", "n3O9phj3hEiwxlXKEz9puR7RfxbAA5s");

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                ResponseBody body = response.body();
                try {
                    if(body!=null) {
                        Log.d("服务器返回的json串:",body.string());
                    } else {
                        Log.d("服务器返回的json串:","是null");
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
                Throwable cause = t.getCause();
                String message = cause.getMessage();
                Log.d("--onFailure:",message);
            }
        });

    }

以上就是普通的post,,get的用法。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值