请教个HttpURLConnection远程连接的问题
if (http_conn.getResponseCode() == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(
(InputStream) http_conn.getInputStream(), "UTF-8"));
msg = in.readLine();
in.close();
}
debug时发现当判断http_conn.getResponseCode()是否是200的时候,请求已经发到服务器了。我的问题如果在服务器处理过程中网络断了,客户端就收不到服务器的返回值,该如何捕捉到这个错误,并作为异常抛出来。现在的情况是我把网断了以后,程序就没有反应了,没有任何异常抛出来。
[最优解释]
HttpURLConnection urlConnection = null;
try {
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
//
urlConnection.setRequestMethod("Get");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String inputLine = null;
in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(), "UTF-8"));// 注意,此处UTF-8
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
}
return sb.toString();
//System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
try{
http_conn = (HttpURLConnection) url.openConnection();
http_conn.setDoOutput(true);
http_conn.setRequestMethod("POST");
http_conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
StringBuffer str_buf = new StringBuffer();
for (int i = 0; i < param.length; i++) {
str_buf.append(param[i]).append("=").append(value[i]).append("&");
}
json = value[1];
OutputStream outStream = http_conn.getOutputStream();
outStream.write(str_buf.toString().getBytes("UTF-8"));
outStream.flush();
outStream.close();
http_conn.setConnectTimeout(20 * 1000);
http_conn.setReadTimeout(20 * 1000);
http_conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) http_conn.getInputStream(), "UTF-8"));
msg = in.readLine();
in.close();
}catch(IOException e){
e.getMessage();
}