简体   繁体   English

如何使用 Android Studio Volley 库将 JSON 数组发送到 HTTP 请求

[英]How to send JSON Array to HTTP request using the Android Studio Volley Library

I have done a lot of research but not been successful.我做了很多研究,但没有成功。

I have an android app.我有一个 android 应用程序。 Where I can add save people name to SQLite database.我可以在其中将保存人名添加到 SQLite 数据库。

I want to have a SYNC button which then pushed the data into MYSQL using the REST API (HTTP request).我想要一个 SYNC 按钮,然后使用 REST API (HTTP 请求)将数据推送到 MYSQL 中。

So firstly, I created a function to get all data from the names table.所以首先,我创建了一个 function 来从名称表中获取所有数据。

        //get the data to to send to mysql
    final Cursor data = mDatabaseHelper.getData();

    //Create an Array list
    final ArrayList<String> listData = new ArrayList<>();


    //Declare json array
    final JSONArray datatoperse = new JSONArray();


    //Store the result in array using while loop
    while (data.moveToNext()){
        //get the value from the database in column 1
        //than add to array list
        listData.add(data.getString(1));

        //append data to json array
        datatoperse.put(data.getString(1));

    }
    System.out.println(datatoperse.toString());

THE system.out.print looks like this system.out.print 看起来像这样

 I/System.out: ["name1","name2","name3"]

I then save the data into the JSON array.然后我将数据保存到 JSON 数组中。 Next, I want to send the HTTP request to the server.接下来,我想向服务器发送 HTTP 请求。

  String url = "server host name";

        JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                final String result = response.toString();
                Log.d("Response","result :" + result);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<String,String>();

                   params.put("array",jsonText);


                return super.getParams();
            }
        }  ;
        mQueue.add(request);

I have a php page where this request gets sent to.我有一个 php 页面,此请求将发送到该页面。

<?php

 //Receive the RAW post data.
$content = $_POST["name"];
//$json = '{"name": "wewqewq"}';
$obj = json_decode($content);


 $insert_stmt = $mysqli_scs->prepare("INSERT INTO xamarinuserregister_ur (name) VALUES (?)");
 $name =$obj->{'name'};


 $insert_stmt->bind_param("s", $name);
 //Execute the statement
 $insert_stmt->execute();


?>

I don't know what I am doing wrong.我不知道我做错了什么。

I am not sure if my JSON is working ok or not.我不确定我的 JSON 是否工作正常。

Can someone help me out please.有人可以帮帮我吗?

Try this code试试这个代码

<?php

// Receive the RAW post data.
$content = file_get_contents("php://input");
// $json = '{"name": "wewqewq"}';
$obj = json_decode($content);

$insert_stmt = $mysqli_scs->prepare("INSERT INTO xamarinuserregister_ur (name) VALUES (?)");
$name = $obj->name;

$insert_stmt->bind_param("s", $name);
// Execute the statement
$insert_stmt->execute();

?>

You can to use my library GridmiAPI .您可以使用我的库GridmiAPI

This is solution for you.这是给你的解决方案。

// Init library YOU CAN WRITE IT ONE TIME
GridmiAPI.init("http://example.com/API/", 8000, JSONObject.class);

// Create request
GridmiAPI.Request request = new GridmiAPI.Request("POST", "load");

// TODO FULL URL EQUAL `STATIC + ENDPOINT` = "http://example.com/API/load"

// Create body JSONArray of the request
JSONArray jsonArrayBody = new JSONArray();
jsonArrayBody.put("Item 1");
jsonArrayBody.put("Item 2");
jsonArrayBody.put("Item 2");

// Add to request
request.setBody(jsonArrayBody);

// Send request
GridmiAPI.onRequest(this, request, new GridmiAPI.Handler.OUT() {

    @Override
    protected void onSuccess(GridmiAPI.Response response) {
        try {
            boolean result = ((JSONObject) response.getData()).getBoolean("result");
            ((TextView) findViewById(R.id.title)).setText(result ? "OK" : "NOT OK");
        } catch (Exception exception) {
            this.onFailed(exception);
        }
    }

    @Override
    protected void onFailed(Exception exception) {
        Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
    }

}).start();

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

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