2017-06-23 5 views
0

AsyncTask経由でバックグラウンドでタスクを実行してもエラーが発生します。AndroidでPOSTメソッドを使用してjsonを送信しますが、常に共振コード400を受信します。サーバはバックグラウンドで実行される場合は正常です。

"java.net.ProtocolException:応答がcom.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStreamで を読まれた後にリクエストボディを書き込むことはできません(HttpURLConnectionImpl.java:203)"

がポイント」 os = urlConnection.getOutputStream(); "

private static void postJsonObject(URL url, JSONObject jsonObject) throws IOException { 


    HttpURLConnection urlConnection = null; 
    OutputStream os = null; 
    BufferedWriter bw = null; 

    int responseCode = -1; 

    try { 
     urlConnection = (HttpURLConnection) url.openConnection(); 
     urlConnection.setDoOutput(true); 
     urlConnection.setDoInput(true); 
     urlConnection.setRequestProperty("Content-Type", "application/json"); 
     urlConnection.setRequestMethod("POST"); 
     urlConnection.connect(); 

     responseCode = urlConnection.getResponseCode(); 
     Log.i("Personal", "HTTP URL CONNECTION Response Code: " + responseCode); 

     os = urlConnection.getOutputStream(); 
     bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 

     bw.write(jsonObject.toString()); 

     connectionSuccess = true; 

    } catch (IOException e) { 
     Log.e("Personal", "Problem sending the json string: ", e); 
    } finally { 
     if(urlConnection!=null){ 
      urlConnection.disconnect(); 
     } 
     if(bw!=null){ 
      bw.close(); 
     } 
     if (os!=null){ 
      os.close(); 
     } 
    } 

}

答えて

1

私はあなたのコードを更新した。この

try { 
     urlConnection = (HttpURLConnection) url.openConnection(); 
     urlConnection.setDoOutput(true); 
     urlConnection.setDoInput(true); 
     urlConnection.setRequestProperty("Content-Type","application/json"); 
     urlConnection.setRequestMethod("POST"); 



     urlConnection.connect(); 
     os = urlConnection.getOutputStream(); 
     bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 

     bw.write(jsonObject.toString()); 

     connectionSuccess = true; 
     responseCode = urlConnection.getResponseCode(); 
     Log.i("Personal", "HTTP URL CONNECTION Response Code: " + responseCode); 



    } catch (IOException e) { 
     Log.e("Personal", "Problem sending the json string: ", e); 
    } 
を試してみてください
関連する問題