0
我需要在Android中獲取POST
請求中的JSON
響應。Android - 從POST請求中讀取JSON
這是我到目前爲止的代碼:
String data = null;
try {
data = URLEncoder.encode("Field1", "UTF-8")
+ "=" + URLEncoder.encode(field1, "UTF-8");
data += "&" + URLEncoder.encode("Field2", "UTF-8") + "="
+ URLEncoder.encode(field2, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(Constants.URL_EMAIL_LOGIN);
// Send POST data request
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
int number = conn.getResponseCode();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
如果ResponseCode是200(都可以),服務器發送了我需要的數據的字符串。沒有問題,我已經發布的代碼處理它沒有問題。 200響應:
"{\r\n \"user\": \"AAAA\",\r\n \"token\": \" \",\r\n \"email\": \"[email protected]\" \r\n}"
但我也需要捕捉錯誤。在這種情況下,服務器返回一個JSON
。這是一個錯誤的響應(我使用Firefox的海報擴展了它):
{"Message":"Field1 is not correct."}
有了這種反應,在這條線我的應用程序崩潰:
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
這是抓住了錯誤:
java.io.FileNotFoundException: [url]
有誰知道我可以從服務器讀取的JSON
?
謝謝!它按預期工作:D –
@ O.D。我很高興它是有幫助的! – jayeshsolanki93