Dun*_*now 3 android http-post http-request android-4.0-ice-cream-sandwich
好吧,这是交易,我编写了一个应用程序,通过HTTP(post)数据从web url请求,数据使用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;
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么?或者我需要改变什么,我现在一直在寻找一点点,我无法让它在android 4上运行.
谢谢!
你需要将它放在异步任务中,它不会在3.0>的主线程中运行
用这个:
public class PostTask extends AsyncTask<Void, String, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
boolean result = false;
//All your code goes in here
//If you want to do something on the UI use progress update
publishProgress("progress");
return result;
}
protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");
}
}
}
Run Code Online (Sandbox Code Playgroud)
您需要在异步任务之外引用它
PostTask posttask;
Run Code Online (Sandbox Code Playgroud)
然后你需要启动它
posttask = new PostTask();
posttask.execute();
Run Code Online (Sandbox Code Playgroud)
几天前我遇到了完全相同的问题,好的
| 归档时间: |
|
| 查看次数: |
6300 次 |
| 最近记录: |