因此,我已向服务器发出了此POST请求,并且服务器将基于参数在Retrofit的errorBody()内返回错误消息。我正在尝试处理服务器返回的纯文本错误,然后将其显示给使用Java的Android应用程序中的用户。以下是我当前的尝试,但这在Logcat中给了我这个错误:
@Url cannot be used with @POST URL (parameter #1)
这是来自服务器的400条响应:
接口:
public interface ChangePickLocationClient
{
@GET
Call<ResponseBody> checkItem(@Url String url, @Header("Authorization") String authToken);
@GET
Call<String> getStringError(@Url String url, @Header("Authorization") String authToken);
@POST("Pick/ChangePickLocationAcceptChange")
Call<String> changePickLocationPOST(@Url String url, @Header("Authorization") String authToken, @Body
ChangePickLocationPostModel changePickLocationPostModel);
}
实施:
private static final String BASE_URL = "http://00.00.00.1234/api/";
Gson mGson = new Gson();
Retrofit retrofit = new Retrofit.Builder().client(new OkHttpClient())
.baseUrl(BASE_URL).addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(mGson))
.build();
ChangePickLocationClient ChangePickLocationClient =
retrofitPOST.create(ChangePickLocationClient.class);
String itemNumber = itemNumberValue.getText().toString();
newPickLocationValue.setText(newPickLocationValue.getText().toString().toUpperCase());
String newPickLocation = newPickLocationValue.getText().toString();
String token = globalClass.getActiveToken();
final ChangePickLocationClient mChangePickLocationInterface =
retrofit.create(ChangePickLocationClient.class);
Call<String> mCallErrorPOST = mChangePickLocationInterface.changePickLocationPOST
(postUrl, "Bearer " + globalClass.getActiveToken(),
changePickLocationPostModel);
call.enqueue(new Callback<ChangePickLocationPostModel>()
{
@Override
public void onResponse(Call<ChangePickLocationPostModel> call,
Response<ChangePickLocationPostModel> response)
{
String mPlainTextResponse = null;
try {
if(response.errorBody() != null)
{
mPlainTextResponse = response.errorBody().string();
}
} catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(ChangePickLocation.this, mPlainTextResponse
,Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<ChangePickLocationPostModel> call, Throwable t)
{
Toast.makeText(ChangePickLocation.this, "Unknown server error!"
,Toast.LENGTH_SHORT).show();
}
});
答案 0 :(得分:0)
当响应为400时,进行的第二个调用必须是clone()调用。这是因为该呼叫不能多次使用,如文档中所述。
使用此:
call.clone().enqueue(new Callback<ChangePickLocationPostModel>()
代替
call.enqueue(new Callback<ChangePickLocationPostModel>()