使用post方法volley将jsonobject作为请求参数传递

时间:2017-10-06 18:44:49

标签: php android android-volley

我只是试图使用JsonRequestObject将值发送到php脚本并接收json数据但是代码下方无法正常工作

package com.demo.volleyjsondemo;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.demo.volleyjsondemo.Utils.Constants;
import com.demo.volleyjsondemo.Utils.RequestSingleTone;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    JsonObjectRequest jsonObjectRequest;
    TextView txtName, txtEmail;
    JSONObject parameters;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        try {
            sendReq();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void init() {
        context = MainActivity.this;
        txtName = (TextView) findViewById(R.id.txtName);
        txtEmail = (TextView) findViewById(R.id.txtEmail);
    }

    private void sendReq() throws JSONException {

        //just to demonstrate how to send parameters with json request
        parameters = new JSONObject();
        try {
            parameters.put(Constants.NAME, "jack");
            Log.e("paramter",parameters.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //jsonobjectrequest to send request and get response in json
        jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST //request method
                , Constants.BASE_URL + Constants.GET_PERSON_DETAILS_URL   //URL of php file
                , new JSONObject(parameters.toString()) //parameters to send to server
                , new Response.Listener<JSONObject>() { //response will come here in case of success
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Log.e("response", response.getString(Constants.NAME));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },
                new Response.ErrorListener() {  //response will come here in case of error
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });

        //add request to singletone
        RequestSingleTone.getInstance(context).addRequest(jsonObjectRequest);
    }
}

php code

<?php
    require_once 'dbconfig.php';


    $name = $_POST['name'];

    //$name="jack";

    $singlePersonInfoQuery = "SELECT * FROM test WHERE name='".$name."'";

    $result = mysqli_query($con,$singlePersonInfoQuery);

    if(mysqli_num_rows($result) > 0){
        $raw = mysqli_fetch_assoc($result);

        echo json_encode(array("name"=>$raw['name'],"email"=>$raw['email']));
    }else{
        echo json_encode(array("name"=>$name,"email"=>"blank"));
    }

?>

我收到以下错误

    10-06 14:36:34.943 5256-5256/com.demo.volleyjsondemo W/System.err: com.android.volley.ParseError: org.json.JSONException: Value perfect<br of type java.lang.String cannot be converted to JSONObject
10-06 14:36:34.943 5256-5256/com.demo.volleyjsondemo W/System.err:     at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:73)
10-06 14:36:34.943 5256-5256/com.demo.volleyjsondemo W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:123)
10-06 14:36:34.943 5256-5256/com.demo.volleyjsondemo W/System.err: Caused by: org.json.JSONException: Value perfect<br of type java.lang.String cannot be converted to JSONObject
10-06 14:36:34.943 5256-5256/com.demo.volleyjsondemo W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
10-06 14:36:34.943 5256-5256/com.demo.volleyjsondemo W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
10-06 14:36:34.943 5256-5256/com.demo.volleyjsondemo W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
10-06 14:36:34.943 5256-5256/com.demo.volleyjsondemo W/System.err:     at com.android.volley.toolbox.JsonObjectRequest.parseNetworkResponse(JsonObjectRequest.java:68)
10-06 14:36:34.943 5256-5256/com.demo.volleyjsondemo W/System.err:  ... 1 more

我猜上面的警告是因为错误的方式在PHP脚本中接收参数..如果我没有通过任何参数或使用stringrequest但我想使用jsonrequestobject我可以&#39 ;了解什么是错的

1 个答案:

答案 0 :(得分:0)

最后回答我自己的问题,在调试我的PHP脚本后,我发现我完成了接收php脚本中的参数..因为我发送参数为jsonobject,没有$ _POST或$ _GET将工作。请参考下面哪个工作很好..我希望它会帮助某人

android代码: -

package com.demo.volleyjsondemo;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.demo.volleyjsondemo.Utils.Constants;
import com.demo.volleyjsondemo.Utils.RequestSingleTone;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    JsonObjectRequest jsonObjectRequest;
    TextView txtName, txtEmail;
    Context context;
    Map<String, String> parametersMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        try {
            sendReq();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void init() {
        context = MainActivity.this;
        txtName = (TextView) findViewById(R.id.txtName);
        txtEmail = (TextView) findViewById(R.id.txtEmail);
    }

    private void sendReq() throws JSONException {

        //just to demonstrate how to send parameters with json request
        parametersMap.put(Constants.NAME, "jack");

        //jsonobjectrequest to send request and get response in json
        jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST //request method
                , Constants.BASE_URL + Constants.GET_PERSON_DETAILS_URL   //URL of php file
                , new JSONObject(parametersMap) //parameters to send to server
                , new Response.Listener<JSONObject>() { //response will come here in case of success
            @Override
            public void onResponse(JSONObject response) {
                Log.e("response","received");
                try{
                    txtEmail.setText(response.getString(Constants.EMAIL));
                    txtName.setText(response.getString(Constants.NAME));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },
                new Response.ErrorListener() {  //response will come here in case of error
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });

        //add request to singletone
        RequestSingleTone.getInstance(context).addRequest(jsonObjectRequest);
    }
}

php代码: -

<?php 
    require_once 'dbconfig.php';
    $name = json_decode(file_get_contents("php://input"),true); //sending json object from android..can not receive parameters using $_POST or $_GET

    $singlePersonInfoQuery = "SELECT * FROM `test` WHERE `name`='".$name['name']."'";

    $result = mysqli_query($con,$singlePersonInfoQuery);

    if(mysqli_num_rows($result) > 0){
        $raw = mysqli_fetch_assoc($result);
    }else{

    }
    echo json_encode(array("name"=>$raw["name"],"email"=>$raw["email"]));
?>
相关问题