java后台通过url获取json数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lg491733638/article/details/51507922



/**

* 根据url获取json数据

* @param url
* @return
*/
public static String loadJson(String url) {
StringBuilder json = new StringBuilder();
try {
URL urlObject = new URL(url);
HttpURLConnection uc = (HttpURLConnection) urlObject
.openConnection();
int contentLength = uc.getContentLength();
System.out.println(contentLength);
BufferedReader in = new BufferedReader(new InputStreamReader(uc
.getInputStream(), "utf-8"));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
uc.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();

}

注意:当url中包含中文时,必须在调用方法前进行编码设置


猜你喜欢

转载自blog.csdn.net/lg491733638/article/details/51507922
今日推荐