话不多说 , 先看代码! 先看代码!
/*** Erstellt von David am 2017-7-5. */import com.google.gson.jsonObject; import com.google.gson.jsonParser; import Java.io.BufferedReader; Import Java.io.ioException; Import Java.io.inputStream; wichtige Java.inputStreamReader; HttprequestUtil { / ** * 发起 http 请求并获取结果 * @param Requesturl 请求地址 * / public static jsonObject getXPath (String Requesturl) {String res = ""; JsonObject Object = null; StringBuffer Buffer = new StringBuffer (); try {url url = new URL (Requesturl); HttpurlConnection urlcon = (httpurlConnection) url.openconnection (); if (200 == urlcon.getResponScode ()) {inputStream is = urlcon.getInputStream (); InputStreamReader ISR = New InputStreamReader (IS, "UTF-8"); BufferedReader BR = neuer BufferedReader (ISR); 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 (); } Rückgabeobjekt; } public static jsonObject postdownloadjson (String Pfad, String Post) {url url = null; try {url = new URL (Pfad); HttpurlConnection httpurlConnection = (httpurlConnection) url.openconnection (); httpurlConnection.setRequestMethod ("post"); // 提交模式 // conn.setConnectTimeout (10000); // 连接超时 单位毫秒 // conn.setReadTimeout (2000); // 读取超时 单位毫秒 // 发送 post 请求必须设置如下两行 httpurLConnection.setDooutput (wahr); httpurlConnection.setDoInput (true); // 获取 urlConnection 对象对应的输出流 Printwritriter Printwriter = neuer Pressewriter (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 = neues 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 (Ausnahme e) {e.printstacktrace (); } return null; } // 测试 public static void main (String args []) {jsonObject res = null; // res = getXPath ("http://ip.taobao.com/service/getipinfo.php?ip=63.223.108.42"); res = postdownloadjson ("http://ip.taobao.com/service/getipinfo.php?ip=63.223.108.42", "123"); System.out.println (res); System.out.println (res.get ("Code")); System.out.println (res.get ("Daten")); }}看第一个方法 ,发送 请求获取后台数据 请求获取后台数据 , 其中 , 将返回回来的字符串解析成 JSON 对象用到了 google 的 gson.jar 包 , 用到了其中 JsonParser 的 analysieren 方法。
第二个方法 ,发送 post 数据到后台并获取后台数据。
以上这篇 Java 发起 http 请求获取返回的 json 对象方法就是小编分享给大家的全部内容了 , 希望能给大家一个参考 , 也希望大家多多支持武林网。 也希望大家多多支持武林网。 也希望大家多多支持武林网。