Retrofit 2返回HTML而不是JSON

时间:2017-10-06 21:17:13

标签: java android gson retrofit retrofit2

我正在使用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());
        }
        });
    }

1 个答案:

答案 0 :(得分:2)

请在改装onResponse

中添加以下声明
if (response.isSuccessful()) {
       // Do something
    } else {
       // Do something
    }

或者如果您只想接受回复200

 if (response.code() == 200) {
       // Do something
    } else {
       // do something
    }