最近公司给了一个第三方服务的网址,要我调用后返回需要用到的信息
具体网址:http://www.xxxx.com/xxx-api/xxxx/getXxxByUserId?userId=" + userId+ "&type=1&sceneId=sceneld
直接再网页上显示:
{"longTable":[{"labelName":"message","labelValue":"1507.68","unit":"M"}],"customGroup":[],"crossTable":[]}
后台需要获取并解析
说一下我的实现思路:用http获取页面信息
为方便起见,我把这个封装成一个工具类了
接下来,献上我的工具类
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.net.HttpURLConnection; 5 import java.net.URL; 6 7 public class HttpUtils{ 8 9 public static String getURLContent(String urlStr) { 10 11 //请求的url 12 URL url = null; 13 14 //建立的http链接 15 HttpURLConnection httpConn = null; 16 17 //请求的输入流 18 BufferedReader in = null; 19 20 //输入流的缓冲 21 StringBuffer sb = new StringBuffer(); 22 23 try{ 24 url = new URL(urlStr); 25 26 in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8") ); 27 28 String str = null; 29 30 //一行一行进行读入 31 while((str = in.readLine()) != null) { 32 sb.append( str ); 33 } 34 } catch (Exception ex) { 35 36 } finally{ 37 try{ 38 if(in!=null) { 39 in.close(); //关闭流 40 } 41 }catch(IOException ex) { 42 43 } 44 } 45 String result =sb.toString(); 46 47 return result; 48 } 49 }
方法我已经声明为static,调用直接 类名.方法名 HttpUtil.getURLContent(String URL);
就直接返回字符串了
若要json字符串与java对象进行相互转换,我使用的fastjson转换,再献上我的工具类
pom文件导包:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.21</version> </dependency>
JsonUtil的工具类:
1 import com.alibaba.fastjson.JSON; 2 import com.alibaba.fastjson.JSONObject; 3 4 public final class JsonUtils { 5 /** 6 * 把Java对象转换成json字符串 7 * 8 * @param object 待转化为JSON字符串的Java对象 9 * @return json 串 or null 10 */ 11 public static <T> String parseObjToJson(T object) { 12 String string = null; 13 try { 14 //string = JSON.toJSONString(object); 15 string = JSONObject.toJSONString(object); 16 } catch (Exception e) { 17 System.out.println(e.getMessage()); 18 } 19 return string; 20 } 21 22 /** 23 * 将Json字符串信息转换成对应的Java对象 24 * 25 * @param json json字符串对象 26 * @param c 对应的类型 27 */ 28 public static <T> T parseJsonToObj(String json, Class<T> c) { 29 try { 30 //两个都是可行的,起码我测试的时候是没问题的。 31 //JSONObject jsonObject = JSONObject.parseObject(json); 32 JSONObject jsonObject = JSON.parseObject(json); 33 return JSON.toJavaObject(jsonObject, c); 34 } catch (Exception e) { 35 System.out.println(e.getMessage()); 36 } 37 return null; 38 } 39 40 }
关于工具类的方法调用 上面我已经说了,这个不用我说了吧
恭喜 解析成功