Soyaslan Soyaslan - 3 months ago 23
HTTP Question

Android cannot send post

I am trying to send post to a server from android but it crashes while doing it.
I cannot see if any errors occured, I could not figure out how to monitor http requests in android studio.
Here is my code

try {
String rtoken = FirebaseInstanceId.getInstance().getToken();
Log.v("tokken", rtoken);
URL url = new URL("http://my website.com/yyy");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15001);
conn.setConnectTimeout(15001);
conn.setRequestMethod("POST");
conn.setRequestProperty("pid",jo.getString("parent_id"));
conn.setRequestProperty("sid",jo.getString("parent_id"));
conn.setRequestProperty("token",rtoken);
conn.setDoOutput(true);

OutputStream outputPost = new BufferedOutputStream(conn.getOutputStream());
writeStream(outputPost);
outputPost.flush();
outputPost.close();


} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
}


and the stack trace of crash
(JsonParser.java:105) is the line


OutputStream outputPost = new BufferedOutputStream(conn.getOutputStream());


enter image description here

I am really tired of this problem for hours. Any help will be appreciated, thanks,

Answer

I recommend you to read this article about android Thread management. You are trying to do network on the main thread which freeze the UI, that's why you get the "NetworkOnMainThread" exception. Try starting a new thread and do the networking there like:

(new Thread(){
        @Override public void run(){
            try {
                String rtoken = FirebaseInstanceId.getInstance().getToken();
                Log.v("tokken", rtoken);
                URL url = new URL("http://my website.com/yyy");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15001);
                conn.setConnectTimeout(15001);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("pid",jo.getString("parent_id"));
                conn.setRequestProperty("sid",jo.getString("parent_id"));
                conn.setRequestProperty("token",rtoken);
                conn.setDoOutput(true);

                OutputStream outputPost = new BufferedOutputStream(conn.getOutputStream());
                writeStream(outputPost);
                outputPost.flush();
                outputPost.close();


            } catch (ProtocolException e1) {
                e1.printStackTrace();
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
}).start();
Comments