话不多说,先看代码!,先看代码!
/***由David创建于2017-7-5。 */import com.google.gson.jsonobject; import com.google.gson.jsonparser; import java.io.bufferedreader; import java.io.io.io.io.io.io.io.io.io.io.io.io.io.io.inputstream; import java httprequestutil { / ** *发起http请求并获取结果 * @param requestUrl请求地址 * / public static jsonObject getxpath(string requesturl){string res =“”; jsonObject对象= null; StringBuffer buffer = new StringBuffer();尝试{url url = new url(requestUrl); 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);字符串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(); }返回对象; } public static jsonObject potsdownloadjson(字符串路径,字符串post){url url = null;尝试{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 flush输出流的缓冲printwriter.flush(); //开始获取数据bufferedInputStream bis = new BufferedInputStream(httpurlConnection.getInputStream()); ByTearRayOutputStream bos = new ByTearRayOutputStream(); int len;字节[] arr = new Byte [1024]; while(((len = bis.read(arr))!= -1){bos.write(arr,0,len); bos.flush(); } bos.close(); JSONPARSER PARSE = New JSONPARSER();返回(jsonObject)parse.parse(bos.tostring(“ utf-8”)); } catch(异常E){e.printstacktrace(); }返回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(“代码”)); system.out.println(res.get(“ data”)); }}}看第一个方法,发送
第二个方法, post数据到后台并获取后台数据。
以上这篇java发起http请求获取返回的json,希望能给大家一个参考,也希望大家多多支持武林网。,也希望大家多多支持武林网。