2017-01-13 5 views
-1

私のアンドロイドプロジェクトには、私のサーバーへのHTTP要求用のクラスがあります。 sendGet、sendPost、sendPutのメソッドがあります。次はsendPostメソッドのコードです。Android - サーバーへの投稿要求を送信する際の例外

public JSONObject sendPost(String urlString, String urlParameters) { 

     URL url; 
     JSONObject jObj = null; 
     String json = ""; 

     try{ 

      url = new URL(urlString); 
      HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 

      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Content-Type", "application/json"); 

      connection.setDoOutput(true); 

      DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 
      wr.writeBytes(urlParameters); 
      wr.flush(); 
      wr.close(); 

      BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
      String line; 
      StringBuilder sb = new StringBuilder(); 

      while ((line = br.readLine()) != null) { 
       sb.append(line+"\n"); 
      } 
      br.close(); 

      json = sb.toString(); 

     } catch (MalformedURLException e){ 
      e.printStackTrace(); 
     } 
     catch (IOException e){ 
      e.printStackTrace(); 
     } 

     try{ 
      jObj = new JSONObject(json); 
     } 
     catch (JSONException e){ 
      e.printStackTrace(); 
     } 

     System.out.println(jObj); 

     return jObj; 

    } 

サーバレスポンスをJSONObjectとして返す必要があります。私は自分のサーバーにポストを送信する場合、私は次の例外を取得:

java.io.FileNotFoundException: http://...(私はBufferedReaderのを作るラインで)

org.json.JSONException: End of input at character 0 of(私はjObj =新しいJSONObject(JSON)を行うラインでは、 )

しかし、ブラウザにURLをコピーしても問題はありません。私のサーバーはリクエストを受信して​​処理したため、すべてが機能しているようです。しかし、なぜ私はこれらのエラーと空のJSONObjectを結果として得るのですか?

EDIT:私のNode.jsサーバーで

私は次の形式で応答を送信する:

res.status(200).json({ success: "true" });

または

res.status(400).json({ success: "false", message:"..." });

EDIT 2:

@greenappsは、私は少し私のコードを変更した後、コメント:

... 
    json = sb.toString(); 
    jObj = new JSONObject(json); 

    br.close(); 
    wr.flush(); 
    wr.close(); 

} catch (MalformedURLException e){ 
    e.printStackTrace(); 
} 
catch (IOException e){ 
    e.printStackTrace(); 
} 
catch (JSONException e){ 
    e.printStackTrace(); 
} 

return jObj; 

は今JSONExceptionがなくなっていますが、FileNotFoundExceptionをはまだそこにあり、それが戻ってしまったときjObjはまだ空です。

+0

'wr.close();'ストリームを閉じて接続を終了することもできます。 – greenapps

答えて

0

node.jsサーバーにバグがあり、サーバーの応答コードは502でした。また、BufferedReaderは200個のステータスコードでしか動作しません。それで私は例外があるのです。 BufferedReaderの周りにifがあります。

if(connection.getResponseCode() == 200) { 

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    String line; 
    StringBuilder sb = new StringBuilder(); 

    while ((line = br.readLine()) != null) { 
     sb.append(line + "\n"); 
    } 

    json = sb.toString(); 
    jObj = new JSONObject(json); 

    br.close(); 
}else{ 
    json = "{ success: \"false\" }"; 
    jObj = new JSONObject(json); 
} 
関連する問題