【发布时间】: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