【问题标题】:Passing json to cakephp backend android studio将json传递给cakephp后端android studio
【发布时间】:2021-02-25 15:16:07
【问题描述】:

美好的一天!,我只是想问一些关于如何将 json 字符串从 android 传递到后端的帮助。

这是我上传数据到mysql的代码。我正在使用 okhttp3 库。我认为问题出在请求正文中。我不知道将 json 传递给后端是否正确。

private void uploadToMysql() {
    OkHttpClient client = new OkHttpClient();
    MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    // progress dialog
    pd = new ProgressDialog(getActivity());
    pd.setMessage("Please wait");
    pd.setCancelable(false);
    pd.show();

    Cursor cursor = db.readAllData();
    while (cursor.moveToNext()){
        try {

            obj = new JSONObject();
            obj.put("manufacturersName", cursor.getString(1));
            obj.put("manufacturersCreated", cursor.getString(2));
            obj.put("manufacturersModified", cursor.getString(3));
            obj.put("manufacturersImage", cursor.getString(4));
            jsonArray.put(obj);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    RequestBody body = RequestBody.create(jsonArray.toString(), JSON);
    final Request request = new Request.Builder().url(url).post(body).build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    pd.dismiss();

                    Log.i(TAG, e.getMessage());
                    txtField.setText("Failure !");
                }
            });

        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                        pd.dismiss();

                        txtField.setText(jsonArray.toString());
                        Toast.makeText(getActivity(), "Data successfully uploaded to backend", Toast.LENGTH_SHORT).show();

                }
            });
        }
    });
}

这是我在控制器内部使用的功能。 公共函数 insertToDatabase(){ $this->autoRender = false;

    $manufacturers = $this->Manufacturers->newEntity();  

    // get the contents of the JSON file 
    $jsonCont = file_get_contents('php://input');

    // decode JSON data to PHP array
    $content = json_decode($jsonCont ,true);
    // var_dump($content);

    // fetch the details of manufacturers table 
    $manufacturers->name = $content["manufacturersName"];
    $manufacturers->created =  $content['manufacturersCreated'];
    $manufacturers->modified = $content['manufacturersModified'];
    $manufacturers->image = $content['manufacturersImage'];
    
    if ($this->Manufacturers->save($manufacturers)) {
    // The $article entity contains the id now
    $id = $manufacturers->id;
    }
}

【问题讨论】:

  • CakePHP 版本?
  • 我正在使用 CakePHP 3。

标签: android json cakephp cakephp-3.x


【解决方案1】:

CakePHP 4:

控制器:

public function add()
{
    $this->request->allowMethod(['post', 'put']);

    $manufacturers = $this->Manufacturers->newEmptyEntity();
    $content = $this->request->getData();
    $manufacturers->name = $content["manufacturersName"];
    $manufacturers->created =  $content['manufacturersCreated'];
    $manufacturers->modified = $content['manufacturersModified'];
    $manufacturers->image = $content['manufacturersImage'];
    if ($this->Manufacturers->save($manufacturers)) {
        $message = __('The manufacturer has been saved.');
    } else {
        $message = __('The manufacturer could not be saved. Please, try again.');
    }
    $this->set(compact('manufacturers', 'message'));
    $this->viewBuilder()->setOption('serialize', ['manufacturers', 'message']);
}

阅读更多:

CakePHP 4 REST: https://book.cakephp.org/4/en/development/rest.html

CakePHP 3 REST: https://book.cakephp.org/3/en/development/rest.html

应用控制器:

class AppController extends Controller
{
    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * e.g. `$this->loadComponent('FormProtection');`
     *
     * @return void
     */
    public function initialize(): void
    {
        parent::initialize();

        $this->loadComponent('RequestHandler'); // <-----------
        $this->loadComponent('Flash');
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-05
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2021-11-25
    • 2021-03-19
    相关资源
    最近更新 更多