retrofit网络请求参数为json

来源:互联网 发布:软件安装权限 编辑:程序博客网 时间:2024/05/17 05:53

写了一段时间的安卓,发现retrofit很好用,注解用法比较简单,而且整个结构也很清晰。但是使用过程中发生了很多小错误,查了一晚上的资料才倒腾明白。

仔细检查API【敲黑板】

因为没有好好看api,所以没有注意传的参数是json格式的,所以造成了一直报错的问题。所以要多log看看response返回的问题。

  • 首先修改service
public interface StudentService {    //登录    @Headers({"Content-Type: application/json","Accept: application/json"})//添加header表明参数是json格式的    @POST("api/user/auth")//注解及具体接口url不变    Call<StudentBean> login(@Body RequestBody json);//这里使用@Body注解,且传入的参数为RequestBody}
  • Retrofit中的内容不变,详见上一篇博客
  • 下面更改activity中的代码

    这是我需要作为参数传过去的json
    {
    “username”:”user1”,
    “password”:”123”
    }

private Call<StudentBean> callback;private StudentBean studentBean;private StudentService service;//这里是需要当作参数传过去的json字符串,简单的可以像我这么写//也可以用gson的工具进行转换 这里不多写了    String json = "{\"username\":\""+email+"\",\"password\":\""+password+"\"}";            Log.i("json",json);            RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),json);            callback=service.login(body);            Log.i("request",callback.request().toString());            callback.enqueue(new Callback<StudentBean>() {                @Override                public void onResponse(Call<StudentBean> call, Response<StudentBean> response) {                    Log.i("response",response.toString());                    studentBean =response.body() ;                    showProgress(false);                    Log.i"studentName",student.getName());                }                @Override                public void onFailure (Call <StudentBean > call, Throwable t){                    showProgress(false);                        mPasswordView.setError(getString(R.string.error_incorrect_password));                    mPasswordView.requestFocus();                }            });
阅读全文
0 0
原创粉丝点击