代码如下:返回数据是json数据
spublic static void getData(){
//请求http地址
String urlString = "http//...";
URL url = null;
HttpURLConnection httpURLConnection = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
try {
//建立url
url = new URL(urlString);
//获取连接
httpURLConnection = (HttpURLConnection) url.openConnection();
//获取缓冲流
br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));
String str = null;
//读取数据
while ((str = br.readLine()) != null){
sb.append(str);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (br != null){
try { br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(sb.toString());
}
本文介绍了一个使用Java实现的简单示例,该示例通过发送HTTP请求来获取JSON格式的数据。具体步骤包括创建URL对象、打开连接、读取响应并将其转换为字符串。此过程适用于需要从远程服务器获取数据的应用场景。
3786

被折叠的 条评论
为什么被折叠?



