求java通过http请求获取json数据的demo
package com.binjava.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class MainFrame{
public static void main(String[] args) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL("http://www.yemaxgo.com/connect.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(15000);
connection.setReadTimeout(60000);
connection.connect();
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
result = "{1:"+result+"}";//不是严格的JSON数据格式,补成标准的json数据格式
JsonParser jParser = new JsonParser();
JsonObject jt = (JsonObject) jParser.parse(result);
JsonArray jArray = jt.get("1").getAsJsonArray();
JsonObject subObject=jArray.get(0).getAsJsonObject();
System.out.println("id值为:"+subObject.get("id").getAsInt());
System.out.println("speed值为:"+subObject.get("speed").getAsInt());
System.out.println("pm25为:"+subObject.get("pm25").getAsInt());
System.out.println("temperature(温度)为:"+subObject.get("temperature").getAsInt());
System.out.println("humidity值为:"+subObject.get("humidity").getAsInt());
System.out.println("temperature_warning值为:"+subObject.get("temperature_warning").getAsInt());
System.out.println("gas_warning值为:"+subObject.get("gas_warning").getAsInt());
System.out.println("humidity_warning值为:"+subObject.get("humidity_warning").getAsInt());
System.out.println("lowpower_warning值为:"+subObject.get("lowpower_warning").getAsInt());
System.out.println("mode值为:"+subObject.get("mode").getAsInt());
System.out.println("timing_hour值为:"+subObject.get("timing_hour").getAsInt());
System.out.println("timing_minute值为:"+subObject.get("timing_minute").getAsInt());
System.out.println("timing_second值为:"+subObject.get("timing_second").getAsInt());
System.out.println("update_time值为:"+subObject.get("update_time").getAsString());
subObject=jArray.get(1).getAsJsonObject();
System.out.println("time值为:"+subObject.get("time").getAsString());
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
代码需要导入gson模块包
public static void temp(String isbn) throws IOException{
// 我们需要进行请求的地址:
String temp = "https://api.douban.com/v2/book/isbn/" + isbn;
try {
// 1.URL类封装了大量复杂的实现细节,这里将一个字符串构造成一个URL对象
URL url = new URL(temp);
// 2.获取HttpURRLConnection对象
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// 3.调用connect方法连接远程资源
connection.connect();
// 4.访问资源数据,使用getInputStream方法获取一个输入流用以读取信息
BufferedReader bReader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8"));
// 对数据进行访问
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bReader.readLine()) != null) {
stringBuilder.append(line);
}
// 关闭流
bReader.close();
// 关闭链接
connection.disconnect();
// 打印获取的结果
System.out.println(stringBuilder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map.Entry;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonDemo {
/**
* 打印json信息
* @param jsonStr json字符串
* @throws Exception
*/
public static void printJson(String jsonStr) throws Exception {
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(jsonStr);
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
Iterator<Entry<String, JsonElement>> iterator = jsonObject.entrySet().iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
/**
* 发送get请求
* @param getUrl 请求地址
* @return
* @throws Exception
*/
public static String sendGet(String getUrl) throws Exception {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;
URL url = new URL(getUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp+"\n");
sbf.append("\r\n");
}
result = sbf.toString();
}
return result;
}
public static void main(String[] args) throws Exception {
String jsonStr = null;
String getUrl = "http://www.yemaxgo.com/connect.php";
jsonStr = sendGet(getUrl);
if(jsonStr!=null) {
printJson(jsonStr);
}
}
}
首先你需要一个JSON jar包
然后解析这个JSON对象即可,下面有个链接是HTTP发送JSON数据,解析JSON数据的示例
//解析示例代码
JSONArray userarr = new JSONArray(userjson);
JSONObject userobj = userarr.getJSONObject(0);
user = new User(); //实例化 user 对象,否则报空指针异常
user.setUsername(userobj.getString("username"));
user.setGender(userobj.getString("gender"));
user.setAge(userobj.getInt("age"));
public static void main(String[] args) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL("http://www.yemaxgo.com/connect.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(15000);
connection.setReadTimeout(60000);
connection.connect();
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
System.out.println("结果:"+result);
//解析json
/* [{"id":"9311","speed":"65","pm25":"83","temperature":"268","humidity":"66",""
+ "temperature_warning":"0","gas_warning":"0","humidity_warning":"0",
"lowpower_warning":"0","mode":"1","timing_hour":"0","timing_minute":"0",
"timing_second":"0","update_time":"2018-06-28 21:01:10"},{"time":"184882234"}]*/
JSONArray array = JSON.parseArray(result);
com.alibaba.fastjson.JSONObject jo = array.getJSONObject(0);
System.out.println("id:"+jo.getString("id"));
System.out.println("speed:"+jo.getString("speed"));
System.out.println("pm25:"+jo.getString("pm25"));
System.out.println("temperature:"+jo.getString("temperature"));
System.out.println("humidity:"+jo.getString("humidity"));
System.out.println("temperature_warning:"+jo.getString("temperature_warning"));
System.out.println("gas_warning:"+jo.getString("gas_warning"));
System.out.println("humidity_warning:"+jo.getString("humidity_warning"));
System.out.println("timing_second:"+jo.getString("timing_second"));
System.out.println("update_time:"+jo.getString("update_time"));
System.out.println("timing_hour:"+jo.getString("timing_hour"));
com.alibaba.fastjson.JSONObject jo2 = array.getJSONObject(1);
System.out.println("time"+jo2.getString("time"));
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
记得导一下 com.alibaba.fastjson
将地址直接在浏览器输入,发现结果是[{"id":"9311","speed":"65","pm25":"83","temperature":"268","humidity":"66","temperature_warning":"0","gas_warning":"0","humidity_warning":"0","lowpower_warning":"0","mode":"1","timing_hour":"0","timing_minute":"0","timing_second":"0","update_time":"2018-06-28 21:01:10"},{"time":"184890422"}]
,是一个json数组。所以定义两个对象来接收,当然也可以不定义,直接转换成JSONObject。
public class ObjectOne {
private String id;
private String speed;
private String pm25;
private String temperature;
private String humidity;
private String temperature_warning;
private String gas_warning;
private String humidity_warning;
private String lowpower_warning;
private String mode;
private String timing_hour;
private String timing_minute;
private String timing_second;
private String update_time;
public ObjectOne() {
}
public ObjectOne(String id, String speed, String pm25, String temperature, String humidity, String temperature_warning, String gas_warning, String humidity_warning, String lowpower_warning, String mode, String timing_hour, String timing_minute, String timing_second, String update_time) {
this.id = id;
this.speed = speed;
this.pm25 = pm25;
this.temperature = temperature;
this.humidity = humidity;
this.temperature_warning = temperature_warning;
this.gas_warning = gas_warning;
this.humidity_warning = humidity_warning;
this.lowpower_warning = lowpower_warning;
this.mode = mode;
this.timing_hour = timing_hour;
this.timing_minute = timing_minute;
this.timing_second = timing_second;
this.update_time = update_time;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public String getPm25() {
return pm25;
}
public void setPm25(String pm25) {
this.pm25 = pm25;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public String getTemperature_warning() {
return temperature_warning;
}
public void setTemperature_warning(String temperature_warning) {
this.temperature_warning = temperature_warning;
}
public String getGas_warning() {
return gas_warning;
}
public void setGas_warning(String gas_warning) {
this.gas_warning = gas_warning;
}
public String getHumidity_warning() {
return humidity_warning;
}
public void setHumidity_warning(String humidity_warning) {
this.humidity_warning = humidity_warning;
}
public String getLowpower_warning() {
return lowpower_warning;
}
public void setLowpower_warning(String lowpower_warning) {
this.lowpower_warning = lowpower_warning;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getTiming_hour() {
return timing_hour;
}
public void setTiming_hour(String timing_hour) {
this.timing_hour = timing_hour;
}
public String getTiming_minute() {
return timing_minute;
}
public void setTiming_minute(String timing_minute) {
this.timing_minute = timing_minute;
}
public String getTiming_second() {
return timing_second;
}
public void setTiming_second(String timing_second) {
this.timing_second = timing_second;
}
public String getUpdate_time() {
return update_time;
}
public void setUpdate_time(String update_time) {
this.update_time = update_time;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("{");
sb.append("\"id\":\"")
.append(id).append('\"');
sb.append(",\"speed\":\"")
.append(speed).append('\"');
sb.append(",\"pm25\":\"")
.append(pm25).append('\"');
sb.append(",\"temperature\":\"")
.append(temperature).append('\"');
sb.append(",\"humidity\":\"")
.append(humidity).append('\"');
sb.append(",\"temperature_warning\":\"")
.append(temperature_warning).append('\"');
sb.append(",\"gas_warning\":\"")
.append(gas_warning).append('\"');
sb.append(",\"humidity_warning\":\"")
.append(humidity_warning).append('\"');
sb.append(",\"lowpower_warning\":\"")
.append(lowpower_warning).append('\"');
sb.append(",\"mode\":\"")
.append(mode).append('\"');
sb.append(",\"timing_hour\":\"")
.append(timing_hour).append('\"');
sb.append(",\"timing_minute\":\"")
.append(timing_minute).append('\"');
sb.append(",\"timing_second\":\"")
.append(timing_second).append('\"');
sb.append(",\"update_time\":\"")
.append(update_time).append('\"');
sb.append('}');
return sb.toString();
}
}
public class ObjectTwo {
private String time;
public ObjectTwo() {
}
public ObjectTwo(String time) {
this.time = time;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("{");
sb.append("\"time\":\"")
.append(time).append('\"');
sb.append('}');
return sb.toString();
}
}
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ReadUrl {
public static void main(String args []){
String url = "http://www.yemaxgo.com/connect.php";
try{
String jsonStr = sendGet(url);
System.out.println(jsonStr);
//[{"id":"9311","speed":"65","pm25":"83","temperature":"268","humidity":"66","temperature_warning":"0","gas_warning":"0","humidity_warning":"0","lowpower_warning":"0","mode":"1","timing_hour":"0","timing_minute":"0","timing_second":"0","update_time":"2018-06-28 21:01:10"},{"time":"184884931"}]
JSONArray jsonArray = JSONArray.parseArray(jsonStr);
System.out.println(jsonArray);
JSONObject obj1 = (JSONObject) jsonArray.get(0);
JSONObject obj2 = (JSONObject) jsonArray.get(1);
System.out.println(obj1);
System.out.println(obj2);
ObjectOne objectOne = JSONObject.parseObject(obj1.toJSONString(),ObjectOne.class);
ObjectTwo objectTwo = JSONObject.parseObject(obj2.toJSONString(),ObjectTwo.class);
System.out.println(objectOne);
System.out.println(objectTwo);
}catch(Exception e){
e.printStackTrace();
}
}
public static String sendGet(String getUrl) throws Exception {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;
URL url = new URL(getUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sbf.append(line);
}
result = sbf.toString();
}
return result;
}
}
需要fastjson-1.1.24.jar
此方法必须访问http请求,访问https需要httpclient
具体方法:
@RequestMapping("geturl.do")
public void geturl(HttpServletResponseresponse){
String url = "http://localhost:8080/Test/getUsers.do?id=1";
//new一个stringbuffer
StringBuffer json = new StringBuffer();
try {
//通过url获得连接
URL u = new URL(url);
URLConnection yc = u.openConnection();
//读取返回的数据
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"UTF-8"));
String inputline = null;
while((inputline=in.readLine())!=null){
json.append(inputline);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
//获得jsonobject
JSONObject jo = JSON.parseObject(json.toString());
JSONObject jo2 = jo.getJSONObject("data");
//获得json数组
JSONArray ja = jo2.getJSONArray("users");
JSONObject jo3 = null;
Users user = null;
for (int i = 0; i < ja.size(); i++) {
jo3 = ja.getJSONObject(i);
user = new Users();
user.setId(jo3.getIntValue("id"));
user.setUsername(jo3.getString("username"));
user.setPassword(jo3.getString("password"));
user.setAge(jo3.getIntValue("age"));
user.setSex(jo3.getIntValue("sex"));
System.out.println(user.getUsername());
}
}
package com.ruijie.spl.xhjy;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.ruijie.spl.xhjy.util.bean.Person;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestJsonObject {
public static void main(String[] args) {
String res = post("http://www.yemaxgo.com/connect.php","");
pase(res);
}
private static void pase(String res) {
JSONArray resJsonArray= JSONArray.fromObject(res);
System.out.println(resJsonArray.toString());
JSONObject jsonObject;
for (int j= 0;j<resJsonArray.size();j++){
//获取JsonArray 中的JSONObject
jsonObject=resJsonArray.getJSONObject(j);
//获取JSONObject中的属性值,根据key jsonObject.get("id");
System.out.println( jsonObject.get("id"));
//封装到对应的JavaBean 中,进行其他操作,插入数据库
System.out.println("属性封装对象");
}
}
/**
* httppost
* @param url
* @param postStr
* @return
*/
@SuppressWarnings({ "resource", "deprecation" })
public static String post(String url,String postStr) {
String result = "";
try {
HttpPost post = new HttpPost(url);
StringEntity postEntity = new StringEntity(postStr,"UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
post.setEntity(postEntity);
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(post);
result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
System.out.println(result);
} catch(Exception ex) {
ex.printStackTrace();
}
return result;
}
}
需要的包 httpclient-4.3.6.jar
<!-- JSONObject 开始 jdk15 不加会找不到包-->
net.sf.json-lib
json-lib
2.4
jdk15
<!-- JSONObject 结束 -->
import net.sf.json.JSONObject;
2 import org.apache.commons.httpclient.*;
3 import org.apache.commons.httpclient.methods.GetMethod;
4 import org.apache.commons.httpclient.params.HttpMethodParams;
5 import org.apache.http.HttpEntity;
6 import org.apache.http.HttpResponse;
7 import org.apache.http.client.methods.HttpPost;
8 import org.apache.http.entity.StringEntity;
9 import org.apache.http.impl.client.DefaultHttpClient;
10 import org.apache.http.util.EntityUtils;
11 import java.io.IOException;
12
13 /**
14 * Created by liqun.chen on 2017/5/15.
15 /
16 public class HttpUtil {
17 /*
18 * json 字符串
19 * @param url
20 * @param param
21 * @return
22 /
23 public static String getSerchPersion(String url,String param){
24 / 1 生成 HttpClinet 对象并设置参数 /
25 HttpClient httpClient = new HttpClient();
26 // 设置 Http 连接超时为5秒
27 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
28 / 2 生成 GetMethod 对象并设置参数 /
29 GetMethod getMethod = new GetMethod(url);
30 // 设置 get 请求超时为 5 秒
31 getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
32 // 设置请求重试处理,用的是默认的重试处理:请求三次
33 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
34 String response = "";
35 / 3 执行 HTTP GET 请求 /
36 try {
37 int statusCode = httpClient.executeMethod(getMethod);
38 / 4 判断访问的状态码 /
39 if (statusCode != HttpStatus.SC_OK) {
40 System.err.println("请求出错: "+ getMethod.getStatusLine());
41 }
42 / 5 处理 HTTP 响应内容 /
43 // HTTP响应头部信息,这里简单打印
44 Header[] headers = getMethod.getResponseHeaders();
45 for (Header h : headers)
46 System.out.println(h.getName() + "------------ " + h.getValue());
47 // 读取 HTTP 响应内容,这里简单打印网页内容
48 byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
49 response = new String(responseBody, param);
50 System.out.println("----------response:" + response);
51 // 读取为 InputStream,在网页内容数据量大时候推荐使用
52 // InputStream response = getMethod.getResponseBodyAsStream();
53 } catch (HttpException e) {
54 // 发生致命的异常,可能是协议不对或者返回的内容有问题
55 System.out.println("请检查输入的URL!");
56 e.printStackTrace();
57 } catch (IOException e) {
58 // 发生网络异常
59 System.out.println("发生网络异常!");
60 e.printStackTrace();
61 } finally {
62 / 6 .释放连接 /
63 getMethod.releaseConnection();
64 }
65 return response;
66 }
67 /*
68 * post请求
69 * @param url
70 * @param json
71 * @return
72 */
73 public static JSONObject doPost(String url,JSONObject json){
74 DefaultHttpClient client = new DefaultHttpClient();
75 HttpPost post = new HttpPost(url);
76 JSONObject response = null;
77 try {
78 StringEntity s = new StringEntity(json.toString());
79 s.setContentEncoding("UTF-8");
80 s.setContentType("application/json");//发送json数据需要设置contentType
81 post.setEntity(s);
82 HttpResponse res = client.execute(post);
83 if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
84 HttpEntity entity = res.getEntity();
85 String result = EntityUtils.toString(res.getEntity());// 返回json格式:
86 response = JSONObject.fromObject(result);
87 }
88 } catch (Exception e) {
89 throw new RuntimeException(e);
90 }
91 return response;
92 }
1 //调用
2 public static void main(String arg[]) throws Exception {
3 String url = "http://localhost:8080/";
4 JSONObject params = new JSONObject();
5 params.put("personName", "name");
6 params.put("personCode", "230882xxxxxx2116");
7 JSONObject param2 = new JSONObject();
8 param2.put("pageNo", 1);
9 param2.put("pageSize", 20);
10 params.put("page", param2);
11 String param = "q="+params.toString();
12 //get 请求
13 String ret = getSerchPersion(url, param.toString());
14 System.out.println(ret);
15 // JSONObject jsonResponse=JSONObject.fromObject(param);
16 // JSONObject json = (JSONObject)jsonResponse.get("page");
17 // System.out.println(json.get("pageSize"));
18
19 //post 请求
20 JSONObject jsonObject = doPost(url,params);
21 System.out.println(jsonObject.toString());
22 }