简体   繁体   中英

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. Basically, I've tested my endpoint through postman and it worked. 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". I mean, I've checked my Call code through 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:

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. Even in postman, I've succeeded on sending put request with this kind of json format:

{
    "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:

@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. Please kindly help me:D Thank you.

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. 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. So the solution for this is I created another model class with the same initialization but with different field names cases. As a result, I have 2 model classes with the same fields but only different in upper and lower cases. One is for the PUT method and the other one is for GET method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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