HTTP POST request ANDROID 4 (working in 2.3)?

人走茶凉 提交于 2019-11-30 18:14:31

问题


Ok so, here is the deal, I've coded an app that requests via HTTP (post) data from a web url, the data is returned using JSon arrays and i parse those arrays to get what i want.

Up until there there's no problem using android 2.3.x but when i test it in Android 4 it just does not work at all.

Here is my code:

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;
}

Can anyone tell me what i'm doing wrong? or what i need to change, i've been searching for a little bit now and i can't make it work on android 4.

THANKS!


回答1:


You need to put this in an Async task, it will not run in the main thread in 3.0 >

use this:

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] + " ");
                }

        }
    }

You need a reference to it outside the async task

PostTask posttask;

then you need to start it

posttask = new PostTask();
posttask.execute();

I had the exact same problem a couple of days ago, goodluck




回答2:


With Android 4.0 you cant use http connection without using a Thread (with a runnable, asyinctask ... )

The best you can do is implements a Thread but if you cant do it you cant delete in the android manifest android:targetVersion="14".

If you need some elements of the version 14/higher like Holo theme or something you can configure in

Right clink in the project --> Propierties --> Android --> Project Built Target = 14 or that you want



来源:https://stackoverflow.com/questions/10245731/http-post-request-android-4-working-in-2-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!