java后台通过url获取json数据



/**

* 根据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中包含中文时,必须在调用方法前进行编码设置


你可能感兴趣的:(java后台通过url获取json数据)