无法在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);
}
}
# 1 楼答案
我找到了解决办法。实际上,我从PHP中得到的JSON格式正确,但没有换行符。因此,我在PHP中所做的是,我在回显JSON时添加了
JSON_PRETTY_PRINT
。就这些,问题解决了# 2 楼答案
您应该在PHP脚本中添加“Content Type:”标题
# 3 楼答案
PHP代码:
然后android端代码:
资料来源:http://sampleprogramz.com/android/mysqldb.php
希望这有帮助!祝你好运