首页 > 解决方案 > 为什么使用android改造时没有响应,虽然我可以看到请求?

问题描述

我正在使用 android 改造向我的 laravel 服务器发送一个发布请求。我面临的是我可以在服务器端获取请求正文,但是没有响应(onResponse 方法不运行)。API接口:

package com.example.asus.retrofit;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface Api {
    String BASE_URL="http://405d6d4f.ngrok.io/";
    @POST("execute")
    @FormUrlEncoded
    Call<ServerJsonObject> sendData(@Field("name") String name);

}

我的 ServerJsonObject 类:

public class ServerJsonObject {

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
} 

主要活动:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = retrofit.create(Api.class);
        Call<ServerJsonObject> call = api.sendData("Mathew");

       call.enqueue(new Callback<ServerJsonObject>() {
           @Override
           public void onResponse(Call<ServerJsonObject> call, Response<ServerJsonObject> response) {
               ServerJsonObject x = response.body(); // it doesn't enter here when debugging
               Log.d("data",Integer.toString(x.getAge()));
           }

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

           }
       });
    }
}

我的服务器返回的响应:

{“姓名”:“马修”,“年龄”:22}

我可以在服务器端看到请求正文,如下所示:

名称=马修

标签: androidretrofit

解决方案


推荐阅读