java发起http请求获取返回的Json对象方法
程序员文章站
2024-02-09 17:45:28
话不多说,先看代码!
/**
* created by david on 2017-7-5.
*/
import com.google.gson.jso...
话不多说,先看代码!
/** * created by david on 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; import java.io.inputstreamreader; import java.net.httpurlconnection; import java.net.url; public class 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.getresponsecode()){ inputstream is = urlcon.getinputstream(); inputstreamreader isr = new inputstreamreader(is,"utf-8"); bufferedreader br = new 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(); } return object; } public static jsonobject postdownloadjson(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; } //测试 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("data")); } }
看第一个方法,发送get请求获取后台数据,其中,将返回回来的字符串解析成json对象用到了google的gson.jar包,用到了其中jsonparser的parse方法。
第二个方法,发送post数据到后台并获取后台数据。
以上这篇java发起http请求获取返回的json对象方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。