2

hi everyone am trying to understand how to make a simple post using android here is the code i have

@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();
            }
        }
    });
}

am not sure what am doing wrong i am doing alot of search to find out how to make a simple post and am trying my best
the code seems to crash at this point

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
barq
  • 3,681
  • 4
  • 26
  • 39
Jean Lee
  • 67
  • 2
  • 7
  • Use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare Aug 18 '15 at 22:55
  • HTTP connection does not work on the main thread of the app... – dieter_h Aug 18 '15 at 22:55
  • what a pity there is no stack trace but at least source code and the whole post is nicely formatted! – pelotasplus Aug 18 '15 at 23:00

1 Answers1

3

The app throws NetworkOnMainThreadException, that means you should not execute network related code in main thread. These code will block UI. To prevent this happen, you can use AsyncTask to execute network related code.

Here is an example, create a new class:

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

In public void onClick(View v), execute new NetworkAsyncTask().execute();.

PageNotFound
  • 2,320
  • 2
  • 23
  • 34
  • the system logcat stays idle is there a way to get response normally after submission next page shows ( Thank You ) – Jean Lee Aug 19 '15 at 01:26
  • I think you can add a progressbar, disable the button and show the progressbar when the button is clicked, when asynctask finished, enable the button again. That is my idea. – PageNotFound Aug 19 '15 at 05:00