我试图从我的服务器获得一个JSON
,应该echo json_encode
我一个变量,并返回如下所示的JSON
。但是,每次我尝试调试代码时,我都会在null
上获得builder
。我试图使用.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
希望这可以帮助!祝好运!