我正在开发一个 android 应用程序,它使用 PHP 和 JSON 作为解析器访问 MySQL 数据库。目前我开发它只是为了从数据库表中检索数据。它在模拟器 2.2 (froyo) 上运行良好,但是当我尝试在更高版本的模拟器上运行它时,它不会检索数据。(我已经搜索了一个关于这个的主题,但我没有找到)。
我猜我正在使用的 JSON 类存在某些问题,或者在 JSON 中未使用 HTTP 连接器。在这里我粘贴我的 JsonParse.java 代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.*;
import android.util.Log;
public class JsonParse {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JsonParse() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error Converting Result" + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error Parsing Data" + e.toString());
}
return jObj;
}
}
有什么DefaultHTTPClient
我正在使用的东西还是我应该使用另一个?
对于 URL,我使用了一个名为 ServerProcessor.java 的单独类,它只包含一个方法,如下所示:
public class ServerProcessor extends DbConnection {
String URL = "http://10.0.2.2/myURL/serverandroid.php";
String url = "";
String response = "";
public String retrieveData() {
try {
url = URL + "?operation=retrieve";
response = call(url);
} catch (Exception e) {
}
return response;
}
}
请给我解决它的步骤。提前致谢