如何在android中使用asynchttp从android中读取php的json响应?

时间:2017-10-08 21:27:47

标签: android json asynchttpclient loopj

我正在制作一个程序,将一个数组列表发布到服务器,然后解析数组列表并将其存储在数据库中,但我无法读取响应 因为我无法完成灵魂所以有人可以帮助我

这是android java代码: -

 public void confirmOrder(final String name, final String price, final String quantity, final String cost, final String sellerid)
     {
            AsyncHttpClient httpClient = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            ArrayList<HashMap<String,String>> productList= dbHelper.getAllProducts();

            if(productList.size()!=0)
            {
                pDialog.show();
                params.put("OrderSummary",dbHelper.getAllproducts());
                httpClient.post(APIURL.API_URL, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                    }

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

                    }
                });
            }
            else
            {
                Toast.makeText(getApplicationContext(),"List Empty",Toast.LENGTH_LONG).show();
            }

     }

这里是php代码: -

 $json = $_POST["usersJSON"];

    //Remove Slashes

    if (get_magic_quotes_gpc()){

    $json = stripslashes($json);

    }

    //Decode JSON into an Array
12
    $data = json_decode($json);

    //Util arrays to create response JSON

    $a=array();

    $b=array();

    //Loop through an Array and insert data read from JSON into MySQL DB

    for($i=0; $i<count($data) ; $i++)

    {
      //inserting data in to the database
        i++;
      }
    if(i<0)
     {
          $response['error']=true;
          $response['message']="data inserted";
     }
    else
     {
         $response['error']=false;
         $response['message']="error occured";
         }
    echo json_encode ($response)

如何在我的java程序中读取此响应?

1 个答案:

答案 0 :(得分:0)

在onSuccess中检查http状态代码200然后像这样解析响应字节数组

  String str = IOUtils.toString(responseBody, "UTF-8");

之后使用Gson解析json Sting到任何POJO。 成功和失败都是一样的。