经过测试,第三方站点api返回成功信息是 getInputStream(),而返回错误信息时是 getErrorStream(),他们最终的解析代码都是一样的,所以我把解析代码从try模块中移到了finally模块中,在try和catch模块中分别获取成功的和异常的inputStream信息即可,最终都在finally里面解析,这样不但处理了成功信息和异常信息,而且还避免了重复代码
public static String fetchContentByUrl(String uri, Boolean isPostMethod) { if (StringUtils.isEmpty(uri)) { return null; } HttpURLConnection conn = null; InputStream in = null; try { URL u = new URL(uri); conn = (HttpURLConnection) u.openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); if (isPostMethod) { conn.setRequestMethod("POST"); } in = conn.getInputStream(); } catch (Exception e) { in = conn.getErrorStream(); } finally { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); conn.disconnect(); final byte[] data = bos.toByteArray(); String jsonStr = new String(data); return jsonStr; } catch (IOException e) { e.printStackTrace(); } } return null; }