【发布时间】:2017-10-06 21:17:12
【问题描述】:
我正在使用 Retrofit 2 向 ASP.NET API 发出 POST 请求,我得到的是 HTML 而不是 JSON 作为响应。如果我更改目标 URL 并调用不同的 API 并获得 JSON 响应
这是我的 API 接口
@POST("PosLogin")
Call<CinekinRequest> login();
休息经理
public static final String BASE_URL = "******************";
private API homeApi;
public API getAPi() {
if (homeApi == null) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient.build())
.build();
homeApi = retrofit.create(API.class);
}
return homeApi;
}
执行我的登录()
public void login(final Context context, CinekinRequest login){
Log.e("login", "starting");
Call call = manager.getAPi().login( );
call.enqueue(new Callback<CinekinRequest>() {
@Override
public void onResponse(Call<CinekinRequest> call, Response<CinekinRequest> response) {
Toast.makeText(context, "Success " + response.message(), Toast.LENGTH_SHORT).show();
Log.e("res", "success");
}
public void onFailure(Call<CinekinRequest> call, Throwable t) {
Toast.makeText(context, "error: " + t.getMessage(), Toast.LENGTH_LONG).show();
Log.e("error", t.getMessage());
}
});
}
【问题讨论】:
-
我建议使用 postman 之类的东西来测试 API 以查看返回的响应类型。 API 听起来好像它没有返回 json。
-
只检查一次响应。有时由于错误,您会收到 html 格式的响应。
-
原来,API 实际上是一个配置为返回 JSON 的 SOAP API。我曾经使用过 Retrofit,被告知它是一个 REST API。因此,我更改了我的代码并且它正在工作。谢谢大家。
标签: java android gson retrofit retrofit2