有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我尝试从我的服务器获取一个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);
}

}

共 (3) 个答案

  1. # 1 楼答案

    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

    希望这有帮助!祝你好运

  2. # 2 楼答案

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

    $data = [];
    header('Content-Type: application/json');
    echo json_encode($data);
    
  3. # 3 楼答案

    我找到了解决办法。实际上,我从PHP中得到的JSON格式正确,但没有换行符。因此,我在PHP中所做的是,我在回显JSON时添加了JSON_PRETTY_PRINT。就这些,问题解决了

    echo json_encode($data, JSON_PRETTY_PRINT);