1
我一直在試圖通過使用Retrofit 2.0進行POST請求,但我遇到了一些問題。我很樂意提供任何幫助。 我有這樣的接口:POST請求改進2.0
public interface HZApi {
@POST("URL")
Call<RespBody> register(@Body ReqBody request);
}
這是我的請求和響應類:
public class ReqBody {
@SerializedName("login")
String login;
@SerializedName("password")
String password;
public ReqBody(String login, String password){
this.login = login;
this.password = password;
}
}
public class RespBody {
@SerializedName("login")
String login;
@SerializedName("password")
String password;
@SerializedName("isreg")
int isreg;
}
和我的活動代碼的一部分:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://URL/")
.addConverterFactory(GsonConverterFactory.create())
.build();
HZApi api = retrofit.create(HZApi.class);
ReqBody req = new ReqBody(login,password);
Call<RespBody> call = api.register(req);
call.enqueue(new Callback<RespBody>() {
@Override
public void onResponse(Call<RespBody> call, Response<RespBody> response) {
Toast.makeText(getApplicationContext(),"OK",Toast.LENGTH_SHORT).show();
//answer.setText(response.body().toString());
}
@Override
public void onFailure(Call<RespBody> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
Log.d("MyTag",call.toString(),t);
}
});
,當我嘗試提出要求,JSON拋出: 預期的BEGIN_OBJECT,但BEGIN_ARRAY在第1行第2列路徑$
我試圖做一個沒有特殊類的請求,只是使用一個String參數,但它也不起作用。感謝您的答覆。
Ruslan是正確的,你需要檢查你的服務器返回的是什麼JSON,並根據該 –
@RustemMuzafarov嘗試啓用日誌並檢查實際上是否發送到服務器進行RespBody。要啓用日誌記錄,請閱讀這個簡單的[說明](https://futurestud.io/blog/retrofit-2-log-requests-and-responses)。如果數據實際上被髮送到服務器,這將意味着服務器端的問題。你的請求聲明對我來說看起來不錯。 – Ruslan
Ruslan謝謝你的幫助。我找到了一個解決方案 - 我只需要在我的請求中使用@FormUrlEncoded註釋。 –