【问题标题】:Send JsonObject in POST from android to server [duplicate]将POST中的JsonObject从android发送到服务器[重复]
【发布时间】:2017-06-29 12:43:27
【问题描述】:

我想把这个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

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

【问题讨论】:

标签: java android json server httpurlconnection


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    在 android 中你不能在你的主线程(UI 线程)上做网络。 请使用其他线程,如:How to fix android.os.NetworkOnMainThreadException?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 2014-09-18
      • 2015-08-05
      • 1970-01-01
      • 2012-08-05
      相关资源
      最近更新 更多