简体   繁体   English

Android retrofit 在向 spring 引导发送请求时出错?

[英]Android retrofit error in sending put request to spring boot?

so I'm working on my project.所以我正在做我的项目。 I'm using spring boot as the back end and android java as the front end.我使用 spring 引导作为后端,使用 android java 作为前端。 Basically, I've tested my endpoint through postman and it worked.基本上,我已经通过 postman 测试了我的端点并且它有效。 But when I try to send json data from my android app, it has shown me an error like "Error Code 500: The given ID must not be null".但是当我尝试从我的 android 应用程序发送 json 数据时,它向我显示了一个错误,例如“错误代码 500:给定的 ID 不能为空”。 I mean, I've checked my Call code through Log.d.我的意思是,我已经通过 Log.d 检查了我的呼叫代码。 Here's my method of put request:这是我提出请求的方法:

 public void updateAddress(AddresslistResponse addresslistResponse){
        SharedPreferences preferences = getSharedPreferences("MyPref",0);
        String tokens = preferences.getString("userToken",null);
        Call<AddresslistResponse> call = mainInterface.editAddress("Bearer " + tokens, addresslistResponse);
        call.enqueue(new Callback<AddresslistResponse>() {
            @Override
            public void onResponse(Call<AddresslistResponse> call, Response<AddresslistResponse> response) {
                Log.d("Call request", call.request().toString());
                Log.d("Call request header", call.request().headers().toString());
                Log.d("Response raw header", response.headers().toString());
                Log.d("Response raw", String.valueOf(response.raw().body()));
                Log.d("Response code", String.valueOf(response.code()));

                try {
                    if(response.body()!=null)
                        Toast.makeText(EditDataAlamat.this," response message success "+response.body(),Toast.LENGTH_LONG).show();
                    if(response.errorBody()!=null)
                        Toast.makeText(EditDataAlamat.this," response message error "+response.errorBody().string(),Toast.LENGTH_LONG).show();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<AddresslistResponse> call, Throwable t) {
                Log.e("ERROR: ", t.getMessage());
            }
        });
    }

And here's my log's output:这是我的日志 output:

2020-06-16 11:25:06.278 27478-27478/com.example.my_app D/Call request: Request{method=PUT, url=http://localhost:1111/address/update/, tags={class retrofit2.Invocation=com.example.my_app .Interface.MainInterface.editAddress() [Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbldTSFJJUyIsInNjb3BlcyI6IlJPTEVfQURNSU4iLCJpYXQiOjE1OTIyNzkwODksImV4cCI6MTU5Mj, AddresslistResponse{alamat2 = 'Jl. mangga',telp2 = 'SOLO',telp1 = 'BANDUNG',kota2 = '16512',kota1 = '4568156',alamat1 = 'JL ramai',noPegawai = '14141414'}]}}
2020-06-16 11:25:06.279 27478-27478/com.example.my_app D/Call request header: Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbldTSFJJUyIsInNjb3BlcyI6IlJPTEVfQURNSU4iLCJpYXQiOjE1OTIyNzkwODksImV4cCI6MTU5MjM2NTQ4OX0.EdOBfplxy-RKfPcHA2vfk9PPvPv3UxoQua9ovKbgT7U
2020-06-16 11:25:06.279 27478-27478/com.example.my_app D/Response raw header: Content-Type: application/json;charset=UTF-8
    Transfer-Encoding: chunked
    Date: Tue, 16 Jun 2020 04:25:06 GMT
    Connection: close
2020-06-16 11:25:06.279 27478-27478/com.example.my_app D/Response raw: retrofit2.OkHttpCall$NoContentResponseBody@e938081
2020-06-16 11:25:06.280 27478-27478/com.example.my_app D/Response code: 500

Based on the log shown above that I already pass the value as JSON Object.根据上面显示的日志,我已经将值传递为 JSON Object。 Even in postman, I've succeeded on sending put request with this kind of json format:即使在 postman 中,我也成功发送了这种 json 格式的 put 请求:

{
    "noPegawai": "141414",
    "kota2": "SOLO",
    "telp2": "085264524",
    "alamat2": "Jl. mangga",
    "alamat1": "JL ramai",
    "kota1": "BANDUNG",
    "telp1": "0812856477"
}

I already try to change the calling method in spring boot like this, but still the same error keep showing:我已经尝试像这样更改 spring 启动中的调用方法,但仍然显示相同的错误:

@Transactional
    @Override
    public Alamat updateAlamat(Alamat address) {
        Optional<Alamat> newAddress = alamatRepository.findById(address.getNik());
        newAddress.get().setNoPegawai(address.getNik());
        newAddress.get().setAlamat1(address.getAlamat1());
        newAddress.get().setAlamat2(address.getAlamat2());
        newAddress.get().setKota1(address.getKota1());
        newAddress.get().setKota2(address.getKota2());
        newAddress.get().setTelp1(address.getTelp1());
        newAddress.get().setTelp2(address.getTelp2());
        return alamatRepository.save(newAddress.get());
    }

Is there something that I missed?有什么我错过的吗? I've trying to figure it out for like 2 days and still no progress.我已经尝试了 2 天,但仍然没有任何进展。 Please kindly help me:D Thank you.请帮助我:D 谢谢。

I've found the solution for this.我已经找到了解决方案。 So, in my model class, I initialized the field name based on JSON format from GET request but it should be following the format of Put request instead.因此,在我的 model class 中,我根据 GET 请求的 JSON 格式初始化了字段名称,但它应该遵循 Put 请求的格式。 Example:例子:

//field name for PUT method
@Serialized ("noPegawai")
private String id;

//field name for GET method
@Serialized ("NoPegawai")
private String id

I don't know why this problem happened, right on my table field it is stated exactly the same like "NoPegawai", but the JAVA thing here can only read it (Which is using GET method) but cannot send it to PUT method and returned it as a null value.我不知道为什么会出现这个问题,就在我的表格字段上,它的声明与“NoPegawai”完全相同,但是这里的 JAVA 东西只能读取它(使用 GET 方法)但不能将其发送到 PUT 方法和将其作为 null 值返回。 So the solution for this is I created another model class with the same initialization but with different field names cases.因此,解决方案是我创建了另一个 model class 具有相同的初始化但具有不同的字段名称情况。 As a result, I have 2 model classes with the same fields but only different in upper and lower cases.结果,我有 2 个 model 类具有相同的字段,但大小写不同。 One is for the PUT method and the other one is for GET method.一种用于 PUT 方法,另一种用于 GET 方法。

I don't know if this will be the right solution for other cases, but in my case, it works.我不知道这是否是其他情况的正确解决方案,但就我而言,它有效。 If anyone can tell me the best solution for this, I'll appreciate it:D如果有人能告诉我最好的解决方案,我将不胜感激:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM