【发布时间】:2012-04-20 11:53:34
【问题描述】:
好吧,这就是交易,我编写了一个应用程序,该应用程序通过来自 web url 的 HTTP(post)数据请求,数据使用 JSon 数组返回,我解析这些数组以获得我想要的。
直到使用 android 2.3.x 没有问题,但是当我在 Android 4 中测试它时,它根本不起作用。
这是我的代码:
public boolean testConexio(){
boolean status = false;
String rutaServer = "URL.php";
//Log.e("log_tag", "Ruta server: "+rutaServer);
InputStream is = null;
String result = "";
String temporal;
//Valors a demanar/enviar
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("param1",config.getUserDB())); // parametros POST!
nameValuePairs.add(new BasicNameValuePair("param2",config.getPassDB())); // parametros POST!
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(rutaServer);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8")); // valors POST UTF 8 coded <-- I KNOW! this is the way i need them spanishfag here
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//Convierte la respuesta a String
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8); // again, spanishfag here
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//Parse la respuesta JSon
try{
JSONObject jArray = new JSONObject(result);
temporal = jArray.getString("status");
if(temporal.equals("true")){
status = true;
}
Log.i("log_tag","Status: "+jArray.getString("status"));
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return status;
}
谁能告诉我我做错了什么?或者我需要改变什么,我现在一直在寻找一点点,但我无法让它在 android 4 上运行。
谢谢!
【问题讨论】:
-
假设你得到
android.os.NetworkOnMainThreadException...你不应该在主线程上进行互联网操作...使用线程(fx.: AsyncTask) -
作为使用 AsyncTask 的替代方法,请查看答案 here 看看是否有帮助。
-
@yorkw 这个答案真的是非常糟糕的做法,在异步任务中这样做会好 100%。
-
@SmartLemon,正如我在最后的回答中提到的那样。另请注意,您所说的真正糟糕的做法是存在的,并且在 API 级别 11 之前允许很长时间。
标签: android http-post android-4.0-ice-cream-sandwich http-request