我有一个使用 JSON 通过 PHP 脚本与 SQL 数据库通信的 Java 应用程序。我之前使用 JSON 对数组进行 json_encode,效果很好,您可以使用每个条目的键调用 Java 中的值。但是现在,我在 PHP 中对一个字符串进行了 json_encoded,如下所示:
json_encode("Succes!");
现在,我如何在 Java 业务方面请求该值?我需要一些东西jsonResponse.getString('key');
作为钥匙。关键是什么...
我希望你能理解我的问题...
public String send(String username, String password, String database){
//Create a HTTPClient as the form container
HttpClient httpclient;
//Use HTTP POST method
HttpPost httppost;
//Create an array list for the input data to be sent
ArrayList<NameValuePair> nameValuePairs;
//Create a HTTP Response and HTTP Entity
HttpResponse response;
HttpEntity entity;
//Create new default HTTPClient
httpclient = new DefaultHttpClient();
//Create new HTTP POST with URL to php file as parameter
httppost = new HttpPost("http://192.168.144.150/login/add.php");
String pass = md5(password);
//Next block of code needs to be surrounded by try/catch block for it to work
try {
//Create new Array List
nameValuePairs = new ArrayList<NameValuePair>();
//place them in an array list
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", pass));
nameValuePairs.add(new BasicNameValuePair("database", database));
//Add array list to http post
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//assign executed form container to response
response = httpclient.execute(httppost);
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode()== 200){
//assign response entity to http entity
entity = response.getEntity();
//check if entity is not null
if(entity != null){
//Create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create new JSON Object. assign converted data as parameter.
//JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
JSONArray a = new JSONArray(convertStreamToString(instream));
//assign json responses to local strings
String res = a.getString(0);
//Return the json response to the gui
return res;
} else {
//Toast.makeText(this, "kapot", Toast.LENGTH_SHORT).show();
return new String("De entiteit is leeg. Kortom: kapot");
}
} else {
//Toast.makeText(this, "statuscode was niet 200", Toast.LENGTH_SHORT).show();
return new String("De statuscode was niet 200.");
}
} catch(Exception e){
e.printStackTrace();
//Display toast when there is a connection error
//Change message to something more friendly
//Toast.makeText(this, "verbindingsproblemem", Toast.LENGTH_SHORT).show();
return new String("Er is een fout opgetreden. Controleer a.u.b. uw gegevens en de internetverbinding.");
}
不要介意荷兰语部分,这并不重要。