第一种:
1 public static String getURLContent(String urlStr) { 2 /** 网络的url地址 */ 3 URL url = null; 4 /** http连接 */ 5 HttpURLConnection httpConn = null; 6 /**//** 输入流 */ 7 BufferedReader in = null; 8 StringBuffer sb = new StringBuffer(); 9 try { 10 url = new URL(urlStr); 11 in = new BufferedReader(new InputStreamReader(url.openStream(), "GBK")); 12 String str = null; 13 while ((str = in.readLine()) != null) { 14 sb.append(str); 15 } 16 } catch (Exception ex) { 17 18 } finally { 19 try { 20 if (in != null) { 21 in.close(); 22 } 23 } catch (IOException ex) { 24 } 25 } 26 String result = sb.toString(); 27 System.out.println(result); 28 return result; 29 }
第二种:
1//http请求返回json 2 public static String httpGetJson(String url){ 3 String result = ""; 4 BufferedReader in = null; 5 try { 6 String urlNameString = url; 7 URL realUrl = new URL(urlNameString); 8 // 打开和URL之间的连接 9 URLConnection connection = realUrl.openConnection(); 10 // 设置通用的请求属性 11 //connection.setRequestProperty("contentType", "utf8"); 12 connection.setReadTimeout(5000); 13 connection.setRequestProperty("accept", "*/*"); 14 connection.setRequestProperty("connection", "Keep-Alive"); 15 connection.setRequestProperty("user-agent", 16 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 17 // 建立实际的连接 18 connection.connect(); 19 // 获取所有响应头字段 20 // Map<String, List<String>> map = connection.getHeaderFields(); 21 22 23 // 定义 BufferedReader输入流来读取URL的响应 24 in = new BufferedReader(new InputStreamReader( 25 connection.getInputStream(),"UTF-8"));//防止乱码 26 String line; 27 while ((line = in.readLine()) != null) { 28 result += line; 29 } 30 } catch (Exception e) { 31 //System.out.println("发送GET请求出现异常!" + e); 32 e.printStackTrace(); 33 result=""; 34 } 35 // 使用finally块来关闭输入流 36 finally { 37 try { 38 if (in != null) { 39 in.close(); 40 } 41 } catch (Exception e2) { 42 e2.printStackTrace(); 43 } 44 } 45 // System.out.println("123"); 46 47 return result; 48 }