传回空值

时间:2019-05-09 13:59:20

标签: java android api retrofit2

这是我的代码,我不知道这是怎么回事。这只是一个简单的登录。

主要活动

public class MainActivity extends AppCompatActivity {

    private login login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://services.hanselandpetal.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        login = retrofit.create(login.class);

        Button btnLogin = findViewById(R.id.btn_log_out);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                login.isLogin("eslam@yahoo.com","123").enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            assert response.body() != null;
                            String MyResult = response.body().string();
                            Log.d("sample",MyResult);
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }
        });

    }

}

界面

public interface login {

    @GET("api/register")
    Call<ResponseBody> isLogin(@Query("Email") String Email,@Query("Password") String Password);

}

1 个答案:

答案 0 :(得分:0)

从NullPointerException判断您的response.body()为空。

要找出真正的问题是什么,应该通过在Retrofit配置中添加拦截器来记录网络流量。

为此,请将compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'添加到您的应用依赖项中,与gradle同步,然后将Retrofit代码更改为:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 

// set your desired log level
logging.setLevel(Level.BODY);

OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); 

// add logging as last interceptor
httpClient.addInterceptor(logging);  // <-- this is the important line!

Retrofit retrofit = new Retrofit.Builder()  
   .baseUrl(API_BASE_URL)
   .addConverterFactory(GsonConverterFactory.create())
   .client(httpClient.build())
   .build();

此后,您应该在android日志中看到您的网络请求/回复。这应该有助于弄清为什么您的响应正文为空。