在Retrofit和rxjava Android中,Put &Delete方法不起作用。

问题描述 投票:0回答:1

我创建Android应用程序与retrofit& rxjava,服务器在nodejs。我创建了post函数,它的工作,但我创建了Put函数,它不工作,它显示成功,但它不影响在mysqlhelp me解决这个问题,它保存我的生活。

我测试了我的Api与邮递员的工作。它的问题在Android改造我不知道它的错误在哪里

MyApi

connection.connect(function(err) {
  if (err) throw err
  console.log('You are now connected with mysql database...')
})

var server = app.listen(3000, function () {
  var port = server.address().port
  console.log("Server listening at", port)
});

app.get('/get', function (req, res) {
   connection.query('select * from customer', function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.get('/get/:id', function (req, res) {
   connection.query('select * from customer where Id=?', [req.params.id], function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.post('/register', function (req, res) {
   var params  = req.body;
   console.log(params);
   connection.query('INSERT INTO customer SET ?', params, function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.put('/update/:id', function (req, res) {
   connection.query('UPDATE `customer` SET `Name`=?,`Address`=?,`Country`=?,`Phone`=? where `Id`=?', [req.body.Name,req.body.Address, req.body.Country, req.body.Phone, req.body.Id], function (error, results, fields) {
      if (error) throw error;
      res.end(JSON.stringify(results));
    });
});

app.delete('/delete/:id', function (req, res) {
   console.log(req.body);
   connection.query('DELETE FROM `customer` WHERE `Id`=?', [req.body.Id], function (error, results, fields) {
      if (error) throw error;
      res.end('Record has been deleted!');
    });
});

INodeJS.java

public interface INodeJS {
    @POST("register")
    @FormUrlEncoded
    Observable<String> insert(@Field("Id") String id,
                                    @Field("Name") String name,
                                    @Field("Address") String address,
                                    @Field("Country") String Country,
                                    @Field("Phone") String Phone);
    @PUT("update/{Id}/")
    @FormUrlEncoded
    Observable<String> update(@Path("Id") String id,
                              @Field("Name") String name,
                              @Field("Address") String address,
                              @Field("Country") String Country,
                              @Field("Phone") String Phone);
}

RetrofitClient.java

public class RetrofitClient {
    private static Retrofit instance;
    public static Retrofit getInstance(OkHttpClient client)
    {
        if(instance == null)
            instance = new Retrofit.Builder()
                    .baseUrl("http://10.0.2.2:3000")
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build();
            return instance;
    }
}

MainActivity.java

INodeJS myApi;
    CompositeDisposable compositeDisposable = new CompositeDisposable();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        Retrofit retrofit = RetrofitClient.getInstance(okHttpClient);
        myApi = retrofit.create(INodeJS.class);

        edit_id = findViewById(R.id.id);
        edit_name = findViewById(R.id.name);
        edit_address = findViewById(R.id.address);
        edit_country = findViewById(R.id.country);
        edit_phone = findViewById(R.id.phone);
        insert = findViewById(R.id.btn_insert);
        update = findViewById(R.id.btn_update);

        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertuser(edit_id.getText().toString(),edit_name.getText().toString(),edit_address.getText().toString(),edit_country.getText().toString(),edit_phone.getText().toString());
            }
        });
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateuser(edit_id.getText().toString(),edit_name.getText().toString(),edit_address.getText().toString(),edit_country.getText().toString(),edit_phone.getText().toString());
            }
        });
    }
    private void updateuser(String id, String name, String address, String country, String phone)
    {
        compositeDisposable.add(myApi.update(id,name,address,country,phone)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Toast.makeText(MainActivity.this,"Data updated",Toast.LENGTH_LONG).show();
            }
        }));
    }
    private void insertuser(String id, String name, String address, String country, String phone) {

        compositeDisposable.add(myApi.insert(id,name,address,country,phone)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
                        clear_edittext();
                    }
                }));
    }

我在使用HttpLoggingInterceptor对所有函数进行更新的同时,还使用了更新函数。

D/OkHttp: --> PUT http://10.0.2.2:3000/update/100/
D/OkHttp: Content-Type: application/x-www-form-urlencoded
D/OkHttp: Content-Length: 53
D/OkHttp: Name=David&Address=sydney&Country=Australia&Phone=234555
D/OkHttp: --> END PUT (53-byte body)
D/OkHttp: <-- 200 OK http://10.0.2.2:3000/update/100/ (110ms)
D/OkHttp: X-Powered-By: Express
D/OkHttp: Connection: keep-alive
D/OkHttp: Content-Length: 169
android node.js retrofit2 rx-java2 okhttp
1个回答
0
投票

只要删除 / 从你的端点的结尾,并像下面这样做。

另外,将你的基础URL设置成这样 "http://10.0.2.2:3000/"

    @FormUrlEncoded
    @PUT("update/{Id}") 
    Observable<String> update(@Path("Id") String id,
                              @Field("Name") String name,
                              @Field("Address") String address,
                              @Field("Country") String Country,
                              @Field("Phone") String Phone);
© www.soinside.com 2019 - 2024. All rights reserved.