首页
登录 | 注册

Java根据URL连接请求JSON数据解析代码

/**
* 方法描述:根据航班URL接连请求,获取航班信息数据(json)
* 属性:url
* 调用:fltJsonDataParser方法中调用
* */
public static String loadJson(String url) {
StringBuilder json = new StringBuilder();
try {
URL urlObject = new URL(url);
URLConnection uc = urlObject.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}

public static String getJsonString(String urlPath) throws Exception {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
// 对应的字符编码转换
Reader reader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
String str = null;
StringBuffer sb = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
sb.append(str);
}
reader.close();
connection.disconnect();
return sb.toString();
}


2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.009 s.
京ICP备10005923号