使用json在php和android之间进行链接

时间:2014-03-27 11:39:38

标签: php android json api doctrine

我正在开发一个Android应用程序,我正在使用php / doctrine来检索数据库中的数据。我将所述数据放在json对象中。

问题是我不知道如何在android上显示它。 这是php代码:

function getTransaction($id) {
  $transaction = $this->getDoctrine()
    ->getRepository('nameBundle:Transaction')
    ->find($id);
  if(!$transaction) {
    throw $this->createNotFoundException('No transaction found'.$id);
  }

  $array = $transaction->toArray();
  $json = json_encode($array);
}

3 个答案:

答案 0 :(得分:1)

请遵循这个简单的教程here

答案 1 :(得分:0)

  1. 您必须在服务器中部署您的PHP代码。
  2. 假设您有返回json
  3. 的网址(http://xxxx.com/getJson.php
  4. 创建HttpClient并拨打电话。
  5. 获取json数据并解析响应并显示。
  6. 更多详情检查此Read Json From url

答案 2 :(得分:0)

您必须首先获得服务器的请求httpPost。

protected Boolean doInBackground(String... params){

    boolean resul = true;

    HttpClient httpClient = new DefaultHttpClient();

HttpPost post = new
         HttpPost("http://example/getinfo.php");

post.setHeader("content-type", "application/json");}

然后解析json对象。

try{
    //Build the json object
    JSONObject dataJson = new JSONObject();


    dataJson.put("lastName", params[0]);
    dataJson.put("phoneNumer", Integer.parseInt(params[1]));

    StringEntity entity = new StringEntity(dataJson.toString());
    post.setEntity(entity);

        HttpResponse resp = httpClient.execute(post);
        String respStr = EntityUtils.toString(resp.getEntity());

        if(!respStr.equals("true"))
            resul = false;
    }
    catch(Exception ex)
    {
        Log.e("Rest","Error", ex);
        resul = false;
    }

    return resul;