繁体   English   中英

无法从 Java 中的 PHP 获取 JSON (Android Studio)

[英]Can't get JSON from PHP in Java (Android Studio)

我尝试从我的服务器获取一个JSON ,它应该echo json_encode我一个变量并返回一个如下所示的JSON 但是,每次我尝试调试代码时,我都会在builder上得到null 我尝试使用仅存储JSON格式数据的.json文件并且它有效。 所以,我不明白为什么我的代码不起作用。 我的代码有问题吗? 先感谢您。

{
  "id":"714184",
  "corpid":"52233",
  "staffMail":"",
  "smartTags":[],
  "formatted_createdDate":"07/02/2018",
  "thirdcontactid":"11210400",
  "customfields":[
  {
     "id":0,
     "status":"ok",
     "formattedVal":""
  },
  {
     "id":2,
     "status":"ok",
     "formattedVal":""
  }
  ]
}

我使用Asynctask方法连接到我的服务器的 Java 代码

public class PHPConnecteur extends AsyncTask<String, Integer, String>{

private HashMap<String, String> parameters;
private String phpToCall;

public PHPConnecteur(HashMap<String, String> params, String phpTC){
    phpToCall = phpTC;
    parameters = params;
}

@Override
protected void onPreExecute(){
    super.onPreExecute();
}

@Override
protected String doInBackground(String... strings) {
    //System.setProperty("http.keepAlive", "false");
    String dataParsed = "";
    try {

        String u = "https://api.asii.fr/api/".concat(phpToCall);
        URL url = new URL(u);

        JSONObject postDataParams = new JSONObject();
        Iterator<HashMap.Entry<String, String>> entries = parameters.entrySet().iterator();
        while (entries.hasNext()) {
            HashMap.Entry<String, String> entry = entries.next();
            postDataParams.put(entry.getKey(), entry.getValue());

        }

        Log.e("params",postDataParams.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (parameters.size() > 1){ // si ce n'est pas la liste d'incident

            conn.setReadTimeout(15000 );
            conn.setConnectTimeout(15000 );
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
        }else{
            conn.setReadTimeout(15000 );
            conn.setConnectTimeout(15000 );
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
        }


        InputStream stream = new BufferedInputStream(conn.getInputStream());//here is where i should get the output from php
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
        StringBuffer builder = new StringBuffer();

        String inputString;
        while ((inputString = bufferedReader.readLine()) != null) {
            builder.append(inputString);// gives me null when debug
        }


        /*JSONObject topLevel = new JSONObject(builder.toString());
        JSONObject main = topLevel.getJSONObject("id");
        dataParsed = String.valueOf(main.getDouble("temp"));*/

        conn.disconnect();
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }


    return dataParsed;


}

@Override
protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);

}

@Override
protected void onPostExecute(final String result) {
    //delegate.onTaskCompleted(result);
}

}

您应该在 PHP 脚本中添加“Content-Type:”标题。

$data = [];
header('Content-Type: application/json');
echo json_encode($data);

我找到了解决方案。 实际上,我从 PHP 获得的 JSON 格式正确,但只是没有换行符。 所以我在 PHP 中所做的是,在回显 JSON 时添加了JSON_PRETTY_PRINT 就这样,问题解决了。

echo json_encode($data, JSON_PRETTY_PRINT);

PHP代码:

<?php
    $host='127.0.0.1';
    $uname='root';
    $pwd='password';
    $db="android";

    $con = mysql_connect($host,$uname,$pwd) or die("connection failed");
    mysql_select_db($db,$con) or die("db selection failed");

    # Request id value that is sent from android 
    $id=$_REQUEST['id'];

    $r=mysql_query("select * from sample where id='$id'",$con);

    while($row=mysql_fetch_array($r))
    {
        $flag[name]=$row[name];
    }

    print(json_encode($flag));
    mysql_close($con);
?>

然后android端代码:

public void select() {
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    nameValuePairs.add(new BasicNameValuePair("id", id));

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.e("pass 1", "connection success ");
    } catch (Exception e) {
        Log.e("Fail 1", e.toString());
        Toast.makeText(getApplicationContext(), "Invalid IP Address",
                Toast.LENGTH_LONG).show();
    }

    try {
        BufferedReader reader = new BufferedReader
                (new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
        Log.e("pass 2", "connection success ");
    } catch (Exception e) {
        Log.e("Fail 2", e.toString());
    }

    try {
        JSONObject json_data = new JSONObject(result);
        // add whatever you would like to parse (all values you are 
        // sending from PHP)
        name = (json_data.getString("name"));
        Toast.makeText(getBaseContext(), "Name : " + name,
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Log.e("Fail 3", e.toString());
    }
}

来源: http : //sampleprogramz.com/android/mysqldb.php

希望这可以帮助! 祝你好运!

暂无
暂无

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

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