Android将发布数据发送到服务器

时间:2013-08-25 05:15:15

标签: android post

这可能是Sending POST data in Android

的副本

我使用此代码使用android

将发布数据发送到服务器
public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.mysite.com/android.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    } 

但是当我运行此应用程序时,它会显示此错误

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.senddata/com.example.senddata.MainActivity}: android.os.NetworkOnMainThreadException

什么问题?有人可以帮忙吗?

3 个答案:

答案 0 :(得分:4)

尝试在setContentView()下面的mainactivityactivity中使用以下代码,以避免networkOnmainThread异常..

if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

但是,使用AsyncTask在后台线程中进行大量操作而不阻塞主线程会很棒!

并参考此链接......

AsyncTask Android example

答案 1 :(得分:1)

使用asInctask在doInBackground off asynctask中调用postData。不要从mainThread

中调用它

答案 2 :(得分:0)

您无法在主线程上使用AsyncTask类来执行与网络相关的任务