当我向服务器发送 POST 请求时,如果响应为 200,我会得到 JSON 正文。但是,对于不成功的请求,服务器会发送 400 响应代码,但我的 android 代码会引发 FileNotFoundException。阅读 400 响应和 200 响应之间有什么区别吗?
StringBuffer responseBuilder = new StringBuffer();
String line = null;
HttpURLConnection conn = null;
OutputStream out = null;
BufferedReader rd = null;
System.setProperty("http.keepAlive", "false");
try
{
conn = (HttpURLConnection) new URL(requestURL).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(NetworkConstants.CONNECTION_TIMEOUT);
conn.setReadTimeout(NetworkConstants.SOCKET_TIMEOUT);
out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
String s = formatParams();
Log.d("-------------------------------------------------->", s);
writer.write(s);
writer.flush();
writer.close();
}
catch (Exception e)
{
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
try
{
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
{
responseBuilder.append(line);
if (!rd.ready())
{
break;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (conn != null)
{
conn.disconnect();
}
}
String response = responseBuilder.toString();
Log.d("@@@@@@@@@@@@@@@@@@@@@@@@@@@", response);
return response;
亲切的问候,