如何在JsonArrayRequest中发送post参数

时间:2017-09-10 11:18:51

标签: php android

我试图将一个post参数发送到我的php文件

     <?php
      $sid = $_POST['sid'];
      ini_set( 'error_reporting', E_ALL );
      ini_set( 'display_errors', true );
      include 'dbconfig.php';
      //include 'sql.php';
      //include 'pass.php';

      ob_start();
      include 'pass.php';
      ob_end_clean() ;
      /* if($_SERVER['REQUEST_METHOD']=='POST'){*/ 


      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      mysqli_set_charset($conn,'utf8');
      if ($conn->connect_error) {
       die("Connection failed: " . $conn->connect_error);
      }
      $sql = "SELECT * FROM lime_questions  where sid=$sid";
      $result = $conn->query($sql);
      if ($result->num_rows >0) {
      // output data of each row
      while($row[] = $result->fetch_assoc()) {
      $tem = $row;
      $json = json_encode($tem, JSON_UNESCAPED_UNICODE);
      }
      } else {
       echo "0 results";
      }
      $data= strip_tags ($json);
      echo str_replace('success','',$data);

      //$encoded=json_decode($json);
      //print_r($encoded);
      //echo json_last_error_msg();

      $conn->close(); 



      ?>

$ sid变量必须从我的jsonarrayrequest发送而不是parse收到的问题,这是我的java代码: 我使用jsonarrayrequest从我的服务器获取数据到我的应用程序

     public void LoadData() {
            Bundle extras = getIntent().getExtras();
            //sid = extras.getString(Login.KEY_URL);
            sid="1994";
            JsonArrayRequest newsReq1 = new JsonArrayRequest(url1, new  
            Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);

                            String sqid = obj.getString("sid");
                            String gid = obj.getString("gid");
                            String id = obj.getString("qid");
                            String q = obj.getString("question");
                            String t = obj.getString("type");
                            insertIntoDB(sqid, gid, id, q, t);
                            test.setText(q);
                            NewsQuestions question = new NewsQuestions(id, 
                            q, t);
                            // adding question to questions array
                            questionsList.add(question);


                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        } finally {

                        }
                    }
                }

            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    System.out.println(error.getMessage());
                }}
            )
            {
                @Override
                protected Map<String, String> getParams() throws 
AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>
();
                    params.put(KEY_URL,sid);

                    return params;
                }

                @Override
                public int getMethod() {
                    try {
                        getParams();
                    } catch (AuthFailureError authFailureError) {
                        authFailureError.printStackTrace();
                    }
                    return super.getMethod();
                }
            };

我的问题是如何从我的Android应用程序发送sid参数到php m = file

3 个答案:

答案 0 :(得分:0)

尝试使用POST方法请求:

    JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, strURL, new JSONObject(mRequestParams), new Response.Listener<JSONArray>() {
     @Override public void onResponse(JSONArray response) { 
    try { //Here you will receive your response
 } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { 
@Override public void onErrorResponse(VolleyError error) { 
//Do what you want to do on error
 } });

答案 1 :(得分:0)

在Android中按照以下步骤操作。

在您的gradle中添加依赖

 compile 'com.loopj.android:android-async-http:1.4.9'

您可以使用以下代码

调用您的json数组列表
 String url="Your url here";
    String sid="1994";
    RequestParams params=new RequestParams();
    params.add("sid",sid);

    new AsyncHttpClient().post(url,params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String rs = new String(responseBody);
            try{
                JSONArray response= new JSONArray(rs);
                for (int i = 0; i < response.length(); i++) {
                    try {

                        JSONObject obj = response.getJSONObject(i);

                        String sqid = obj.getString("sid");
                        String gid = obj.getString("gid");
                        String id = obj.getString("qid");
                        String q = obj.getString("question");
                        String t = obj.getString("type");
                        insertIntoDB(sqid, gid, id, q, t);
                        test.setText(q);
                        NewsQuestions question = new NewsQuestions(id,
                                q, t);
                        // adding question to questions array
                        questionsList.add(question);


                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    } finally {

                    }
                }

            }catch(Exception e){}
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    });

答案 2 :(得分:0)

我终于找到了一个简单的解决方案,这要归功于RESTClient ...我们不应该使用GetParam(),而应该使用GetBody(),它可以工作:

             @Override
        public byte[] getBody() {

            String requestBody = "num_annonce2="+String.valueOf(num_annonce);  //The request body goes in here.
            try {
                return requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }
        }