Error with HTTP POST Connection

2019-09-06 20:22发布

问题:

I am using a class to use HTTP POST & getting data from a data base via php/json and converting it to a string.

The problem is that I am getting "Error in http connection android.os.NetworkOnMainThreadException" in LogCat. I'm testing this on the emulator and I am using the correct port address. I know this because the port works fine in other parts of the application(loading HTML from Localhost). If I run the php file in a desktop browser, it runs fine. I also know that the permissions are set correctly in mySQL for 10.0.2.2 & the user set in the php login file.

So my question is: Has anyone come accross the same issue and if so, have you figured out what the problem was or any ideas for what else I should look for?

Thnx for your help!

public void loadQuery(String p) {

        String qO = getIntent().getStringExtra("QUERY_ORDER");

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            // HttpPost httppost = new HttpPost("http://10.0.2.2/Andaero/php/" +
            // p + qO + ".php");

            //Hard coded the php link to make sure -->

            HttpPost httppost = new HttpPost(
                    "http://10.0.2.2/Andaero/php/regulatory_list_ASC.php");

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            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());
        }

        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line = "0";
            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());
        }

        setListAdapter(new QueryAdapter(this, result));
    }

回答1:

It seems you might be doing network operations on your app's main thread (that's a common reason for that exception to be thrown).

You should never do that. The main thread should be dedicated only to user interaction, and all network interaction should be offloaded to secondary threads (for instance, use AsyncTask).

For more info, a good read is: http://developer.android.com/guide/practices/design/responsiveness.html