JAVA访问http接口得到返回数据

第一种:

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 }
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java日期时间API系列31

  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前

JAVA访问http接口得到返回数据 - HelloWorld