将POST中的JsonObject从android发送到服务器

时间:2017-06-29 12:43:28

标签: java android json server httpurlconnection

我想将此jsonobject finalObject发送到此服务器地址http://www.xxxx.com/app/pruebaurl我正在使用此代码

     try {

                URL url = new URL("http://www.xxxx.com/app/pruebaurl");

                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Content-Type","application/json");
                httpURLConnection.setRequestProperty("Accept", "application/json");
                httpURLConnection.connect();

                OutputStream outputStream = httpURLConnection.getOutputStream();
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
                outputStreamWriter.write(finalObject.toString());
                outputStreamWriter.flush();
                outputStreamWriter.close();

   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

            String line = null;
            StringBuilder sb = new StringBuilder();

            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

            bufferedReader.close();
            result = sb.toString();

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

但是当我通过调试运行代码时,我注意到从行

跳转时
 httpURLConnection.connect();

到行

OutputStream outputStream = httpURLConnection.getOutputStream();

生成错误并转到异常,它告诉我以下

android.os.NetworkOnMainThreadException

我正在处理一个片段,我可以做些什么来解决这个错误。

2 个答案:

答案 0 :(得分:1)

您需要使用AsyncTask来执行网络操作。你无法在主线程上执行它。

答案 1 :(得分:0)

在android中你不允许在你的主线程(UI线程)上做网络。 请使用下面提到的其他主题:How to fix android.os.NetworkOnMainThreadException?

使用AsyncTask或任何线程来解决这个问题。