retrofit網路請求引數為json
阿新 • • 發佈:2018-11-23
寫了一段時間的安卓,發現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();
}
});