通过url抓取第三方的内容

   大家看到标题都会想到用 HttpURLConnection去处理,但是我想说的是我在实现时遇到的问题,之前用这段代码总是去忽略出现异常时的信息处理,总是处理成功的时候,当然这样做在抓取站带你内容时一般不会出问题,抓不到大不了就返回空喽;但是当抓取第三方api时,就出现问题了,人家api返回异常时都是以错误形式返回,光处理成功的api返回结果已经获取不到这异常信息了,导致自己也看不到原因,总以为是网络原因造成的,其实则不然。

   经过测试,第三方站点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;
	}

猜你喜欢

转载自haiwei2009.iteye.com/blog/1631126