2017-06-29 67 views
0

我想這個JSONObject的finalObject發送到該服務器地址http://www.xxxx.com/app/pruebaurl我使用這個代碼從機器人在郵寄的JSONObject服務器

 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 

我正在一個片段,我可以做什麼來解決這個錯誤。

+0

https://stackoverflow.com/a/17063831/3395198 –

回答

1

您需要使用AsyncTask來執行網絡操作。你不能在主線程上執行它。