You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Retrofit调用Post接口失败,求代码修正(PHP接口Postman测试正常)

Retrofit提交数据失败问题修复

你的代码存在几个关键问题导致接口调用失败,以下是修正后的完整代码及问题说明:

核心问题分析

  • 未从输入框获取item、quantity和日期参数,传递给接口的参数为空
  • onFailure方法未实现,无法排查网络连接或请求异常
  • 日期格式可能与PHP接口要求不匹配(Postman测试时使用的格式可能和你代码中的dd/MM/yyyy不同)
  • 未初始化respon和dataItem变量,会导致空指针异常

修正后的代码

public class incomingItemActivity extends AppCompatActivity {
    TextInputEditText etNama;
    TextInputEditText etQuantity;
    TextInputEditText etTanggal;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_incoming_item);
        getSupportActionBar().setTitle("FORM BARANG");

        // 绑定控件
        etNama = findViewById(R.id.NamaItemET);
        etQuantity = findViewById(R.id.QuantityItemET);
        etTanggal = findViewById(R.id.Date);
        button = findViewById(R.id.simpan);

        // 点击事件
        button.setOnClickListener(v -> setAPI());

        // 日期选择器
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        etTanggal.setOnClickListener(v -> {
            DatePickerDialog dialog = new DatePickerDialog(incomingItemActivity.this, (view, year1, month1, dayOfMonth) -> {
                month1 = month1 + 1;
                // 注意:如果接口要求yyyy-MM-dd格式,改成下面注释的写法
                // String date = year1 + "-" + String.format("%02d", month1) + "-" + String.format("%02d", dayOfMonth);
                String date = dayOfMonth + "/" + month1 + "/" + year1;
                etTanggal.setText(date);
            }, year, month, day);
            dialog.show();
        });
    }

    private void setAPI() {
        // 从输入框获取参数
        String item = etNama.getText().toString().trim();
        String quantity = etQuantity.getText().toString().trim();
        String tanggal = etTanggal.getText().toString().trim();

        // 参数校验
        if (item.isEmpty() || quantity.isEmpty() || tanggal.isEmpty()) {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
            return;
        }

        APInterface apInterface = APIclient.getAPIclient().create(APInterface.class);
        // 注意:需要确保APInterface的tambahItem方法接收三个参数(item、quantity、tanggal)
        Call<ResponseItemDatang> call = apInterface.tambahItem(item, quantity, tanggal);
        call.enqueue(new Callback<ResponseItemDatang>() {
            @Override
            public void onResponse(Call<ResponseItemDatang> call, Response<ResponseItemDatang> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ResponseItemDatang itemDatang = response.body();
                    // 这里可以根据接口返回的成功状态判断,比如itemDatang.isSuccess()
                    Toast.makeText(incomingItemActivity.this, "提交成功", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(incomingItemActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish(); // 关闭当前页面
                } else {
                    // 打印错误信息便于排查
                    try {
                        String errorBody = response.errorBody().string();
                        Log.e("API_ERROR", "错误响应: " + errorBody);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(incomingItemActivity.this, "提交失败,请检查输入", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseItemDatang> call, Throwable t) {
                // 处理网络失败情况
                Log.e("API_FAILURE", "请求失败: " + t.getMessage());
                Toast.makeText(incomingItemActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

额外需要检查的点

  1. APInterface接口定义:确保tambahItem方法的参数数量、名称和类型与PHP接口一致,比如:
    @FormUrlEncoded
    @POST("你的接口路径")
    Call<ResponseItemDatang> tambahItem(
        @Field("item") String item,
        @Field("quantity") String quantity,
        @Field("tanggal") String tanggal
    );
    
  2. 日期格式:如果PHP接口要求yyyy-MM-dd格式,修改日期选择器中的日期拼接逻辑为year1 + "-" + String.format("%02d", month1) + "-" + String.format("%02d", dayOfMonth)
  3. 权限配置:确保AndroidManifest.xml中添加了网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    

内容的提问来源于stack exchange,提问作者Ahmad Fauzan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:32:03