1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > bos 获取数据库连接_java解析数据接口获取json对象

bos 获取数据库连接_java解析数据接口获取json对象

时间:2023-01-02 12:15:29

相关推荐

bos 获取数据库连接_java解析数据接口获取json对象

最近小编在做项目的时候,需要解析一个url以获取其数据,开始我为简便,使用了Postman这个工具来解析,也获取了json对象。

但后也发现,它没法直接连接数据库,也就是说这些数据不能直接存入数据库,经过查询,使用node.js作为中介可以解决这个问题,后又发现,连接后一次只能向数据库post一个对象,后就直接使用java解析吧!

方法很多,在这使用常用HTTP方法的POST和GET为例吧,区别什么的自己百度吧!

首先就是导入所需的架包,我是用的是gson.jar,在后台回复json就能获取!

1、先看get方法

public static JsonObject getPath(String requestUrl){String res=""; JsonObject object = null; StringBuffer buffer = new StringBuffer(); try{URL url = new URL(requestUrl);//获取url HttpURLConnection urlCon= (HttpURLConnection)url.openConnection();//得到链接 if(200==urlCon.getResponseCode()){//如果资源存在InputStream is = urlCon.getInputStream();//得到网络的输入流InputStreamReader isr = new InputStreamReader(is,"utf-8");//编码格式BufferedReader br = new BufferedReader(isr);//存入Buffer缓冲区String str = null;while((str = br.readLine())!=null){buffer.append(str);}br.close();isr.close();is.close();res = buffer.toString();JsonParser parse =new JsonParser();object = (JsonObject) parse.parse(res); } }catch(IOException e){e.printStackTrace(); } return object;}

2、POST方法

public static JsonObject postJson(String path,String post){URL url = null; try {url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST");// 提交模式conn.setConnectTimeout(10000);//连接超时单位毫秒conn.setReadTimeout(2000);//读取超时单位毫秒 // 发送POST请求必须设置如下两行 httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); // 获取URLConnection对象对应的输出流 PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream()); // 发送请求参数 printWriter.write(post);//post的参数 xx=xx&yy=yy // flush输出流的缓冲 printWriter.flush(); //开始获取数据 BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len; byte[] arr = new byte[1024]; while((len=bis.read(arr))!= -1){bos.write(arr,0,len);bos.flush(); } bos.close(); JsonParser parse = new JsonParser(); return (JsonObject)parse.parse(bos.toString("utf-8")); } catch (Exception e) {e.printStackTrace(); } return null; }

3、在主方法中的测试

public static void main(String args [] ) {JsonObject res = null;res=getPath("/trafficindex/city/roadrank?cityCode=307&roadtype=0"); //res = postJson("/trafficindex/city/roadrank?cityCode=307&roadtype=0","ip=63.223.108.42");/System.out.println(res);JsonObject jObject = (JsonObject) res.get("data"); //System.out.println(res.get("data")); JsonArray array = jObject.get("list").getAsJsonArray(); for (int i = 0; i < array.size(); i++) {JsonObject sObject = array.get(i).getAsJsonObject(); System.out.println("id:"+ sObject.get("id").getAsString());} }

4、我用于项目中的结果展示

有问题大家一起探讨,一起学习,一起进步!

欢迎关注“Java引导者”,我们分享最有价值的Java干货文章,助力您成为有思想的Java开发工程师!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。