Reputation: 846
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());
I am really tired of this problem for hours. Any help will be appreciated, thanks,
Upvotes: 0
Views: 302
Reputation: 3031
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();
Upvotes: 1
Reputation: 1156
You are not allowed to connect to the network on the main thread (ie. MainActivity or another View).
Instead, create an AsyncTask
and connect to the web from there.
Upvotes: 2