记录Retrofit的post,get用法。

来源:互联网 发布:matlab符号矩阵行列式 编辑:程序博客网 时间:2024/05/16 07:24

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

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的用法。



原创粉丝点击