關於retrofit的Post請求
阿新 • • 發佈:2019-01-10
- 首先網上的講解一大堆,這裡只是自己當時的問題,或者是介面的問題,現在吧寫出來,為了下次使用
- 為嘛的介面是 http:xxxxx /xxx/xxx
- 然後需要是post請求 方式是 {“dev”:”xxxxxooooo”}
- 自己找了一大堆,最後解決ok,下面程式碼
BASE_URL = "https://xxxxxx.xxx/xxxx/";
//http服務介面
public interface ApiService {
@POST("report")
Call<ResultBean> getResult (@Body BodyPost jsonBean);
}
ResultBean ----》代表請求結果後的 實體類
BodyPost ----》代表你要進行請求體 body來進行post請求的 實體類
比如我上面要求是{"dev" :"xxxxxooooo"}, 則body類是
public class BodyPost {
private String dev ;
public BodyPost(String dev) {
this.dev = dev;
}
}
//最後是請求程式碼
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppUrl.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
mApiService = retrofit.create(ApiService.class);
String xxxx= JsonUtil.changeArrayDateToJson(getjsonbean);
//xxxx代表鍵值對的 值!!!!
mApiService.getResult( new BodyPost(xxxx))
.enqueue(new Callback<ResultBean>() {
@Override
public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
if (!response.isSuccessful()){
try {
Log.d("no success" , response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}else {
Logutils.d("成功結果" , response.body().toString() + "");
}
}
@Override
public void onFailure(Call<ResultBean> call, Throwable t) {
t.printStackTrace();
}
});