REASON
访问豆瓣图书的api,因为图书馆的书很多豆瓣上没有。需要写一个方法获取找不到书时的错误信息。
如:http://api.douban.com/v2/book/isbn/123123 后面的123123是随便填的错误的ISBN码。
网页看的话会返回一段信息,要获取的就是它。
ERROR
然后诡异的事发生了。按照下面的代码获取不到Error message,getErrorStream()会返回null,但如果把中间那行的注释去掉,getErrorStream()就有返回信息,可是定义的map完全没有引用呀。
String urlNameString = "http://api.douban.com/v2/book/isbn/123456?";
URLConnection connection = new URL(urlNameString).openConnection();
connection.connect();
//Map<String, List<String>> map = connection.getHeaderFields();
BufferedReader in = new BufferedReader(new InputStreamReader(
((HttpURLConnection) connection).getErrorStream()));
System.out.println("error:"+in.readLine());
FIND
同一个实验室的学弟给出了思路。
原方法的解释是"an error stream if any, null if there have been no errors, the connection is not connected or the server sent no useful data."。
在连接建立后服务器端并没有发数据,Stream是空的,只有在进行了getHeaderFields()操作后才会激活服务器进行数据发送,实验一下,把getHeaderFields()换成connection.getExpiration(); 错误信息依然成功返回。bingo!