Android OutputStream os = conn.getOutputStream();崩溃的应用程序

时间:2015-08-18 22:52:36

标签: android

大家好我想了解如何使用android制作一个简单的帖子这里是我的代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // url where the data will be posted
    Button clickButton = (Button) findViewById(R.id.button);
    clickButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                URL url = new URL("http://www.macrumors.com/share.php");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("name", "paramValue1")
                        .appendQueryParameter("email", "paramValue2@yahoo.com")
                        .appendQueryParameter("storytitle", "paramValue2@yahoo.com")
                        .appendQueryParameter("story", "paramValue1")
                        .appendQueryParameter("username", "paramValue2@yahoo.com")
                        .appendQueryParameter("submit", "submit");


                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();

                conn.connect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

我不确定我做错了什么我正在做很多搜索以找出如何做一个简单的帖子并且我尽力了代码似乎在此时崩溃 < BR />

OutputStream os = conn.getOutputStream();

logcat的

Device driver API version: 10
    User space API version: 10
08-18 23:37:33.038  26003-26003/httpp.myapplication D/﹕ mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Thu Oct 25 08:43:05 KST 2012
08-18 23:37:33.068  26003-26003/httpp.myapplication D/OpenGLRenderer﹕ Enabling debug mode 0
08-18 23:37:35.648  26003-26003/httpp.myapplication W/System.err﹕ android.os.NetworkOnMainThreadException
08-18 23:37:35.653  26003-26003/httpp.myapplication W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
08-18 23:37:35.653  26003-26003/httpp.myapplication W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-18 23:37:35.653  26003-26003/httpp.myapplication W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-18 23:37:35.653  26003-26003/httpp.myapplication W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-18 23:37:35.653  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
08-18 23:37:35.653  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
08-18 23:37:35.653  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
08-18 23:37:35.653  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
08-18 23:37:35.653  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
08-18 23:37:35.658  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
08-18 23:37:35.658  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
08-18 23:37:35.658  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
08-18 23:37:35.658  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
08-18 23:37:35.658  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
08-18 23:37:35.658  26003-26003/httpp.myapplication W/System.err﹕ at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at httpp.myapplication.MainActivity$1.onClick(MainActivity.java:52)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at android.view.View.performClick(View.java:4232)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at android.view.View$PerformClick.run(View.java:17298)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:615)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4921)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
08-18 23:37:35.663  26003-26003/httpp.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
08-18 23:37:35.668  26003-26003/httpp.myapplication W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
08-18 23:37:35.668  26003-26003/httpp.myapplication W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
08-18 23:37:58.673  26003-26003/httpp.myapplication W/IInputConnectionWrapper﹕ getSelectedText on inactive InputConnection
08-18 23:37:58.673  26003-26003/httpp.myapplication W/IInputConnectionWrapper﹕ setComposingText on inactive InputConnection
08-18 23:37:58.673  26003-26003/httpp.myapplication W/IInputConnectionWrapper﹕ getExtractedText on inactive InputConnection
08-18 23:56:40.378  26003-26006/httpp.myapplication D/dalvikvm﹕ GC_CONCURRENT freed 362K, 16% free 9613K/11335K, paused 10ms+1ms, total 42ms

1 个答案:

答案 0 :(得分:2)

应用程序抛出NetworkOnMainThreadException,这意味着您不应该在主线程中执行与网络相关的代码。这些代码将阻止UI。为防止发生这种情况,您可以使用AsyncTask执行与网络相关的代码。

这是一个例子,创建一个新类:

class NetworkAsyncTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {
            URL url = new URL("http://www.macrumors.com/share.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("name", "paramValue1")
                    .appendQueryParameter("email", "paramValue2@yahoo.com")
                    .appendQueryParameter("storytitle", "paramValue2@yahoo.com")
                    .appendQueryParameter("story", "paramValue1")
                    .appendQueryParameter("username", "paramValue2@yahoo.com")
                    .appendQueryParameter("submit", "submit");


            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();

            conn.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

public void onClick(View v)中,执行new NetworkAsyncTask().execute();