话不多说 , 先看代码!
/*** Criado por David em 2017-7-5. */importar com.google.gson.jsonObject; importar com.google.gson.jsonparser; importar java.io.bufferedReader; importar java.io.ioException; import java.io.inputStream; import java.io.iniMreamer; import java.net.htttTttTaM; Httprequestutil { / ** * 发起 http 请求并获取结果 * @param requesturl 请求地址 * / public static jsonObject getxPath (string requesturl) {string res = ""; Objeto jsonObject = null; StringBuffer buffer = new StringBuffer (); tente {url url = novo url (requesturl); HttpurlConnection urlcon = (httpurlConnection) url.openconnection (); if (200 == urlcon.getResponsecode ()) {inputStream is = urlcon.getInputStream (); InputStreamReader isr = new InputStreamReader (IS, "UTF-8"); BufferErader BR = new BufferredReader (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 (); objeto = (jsonObject) parse.parse (res); }} catch (ioexception e) {e.printStackTrace (); } retornar objeto; } public static jsonObject postdownloadjson (caminho da string, string post) {url url = null; tente {url = new url (caminho); HttpurlConnection httpurlConnection = (httpurlConnection) url.openconnection (); httpurlConnection.setRequestMethod ("post"); // 提交模式 // Conn.SetConnectTimeout (10000); // 连接超时 单位毫秒 // Conn.SetReadTimeout (2000); // 读取超时 单位毫秒 单位毫秒 // 发送 post 请求必须设置如下两行 httpurlConnection.SetOutput (True); httpurlConnection.setDoinput (true); // 获取 urlConnection 对象对应的输出流 printWriter printWriter = new PrintWriter (httpurlConnection.getOutputStream ()); // 发送请求参数 PrintWriter.Write (post); // post 的参数 xx = xx & yy = yy // flush 输出流的缓冲 printWriter.flush (); // 开始获取数据 bufferInputStream bis = new bufferInputStream (httpurlConnection.getInputStream ()); ByteArrayOutputStream bos = new ByteArrayOutputStream (); int len; byte [] arr = novo 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 (Exceção e) {e.printStackTrace (); } retornar nulo; } // 测试 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 ("dados")); }}看第一个方法 ,发送 obtenha 请求获取后台数据 , 其中 , 将返回回来的字符串解析成 json 对象用到了 google 的 gson.jar 包 , 用到了其中 jsonparser 的 parse 方法。
第二个方法 ,发送 Post 数据到后台并获取后台数据。
以上这篇 java 发起 http 请求获取返回的 json 对象方法就是小编分享给大家的全部内容了 , 希望能给大家一个参考 , 也希望大家多多支持武林网。