您的位置:首页 > 移动开发 > Android开发

Android开发-使用工具类进行网络请求数据

2018-12-12 14:53 417 查看

如何用网络请求数据呢?

第一步 创建一个工具类NetWorks 在工具类中写一个方法(getJson)
这个类里可以写很多方法 不仅仅限于网络请求数据 比如常见的还有判断网络的连接状态等等…在其他的页面可以调用到这个工具类里的方法

public class NetWorks {

//网络请求数据 的方法
public static String getJson(String urlString){
try {
URL url = new URL( urlString );
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) );
//按行读取
String temp="";
String json="";
while ((temp=reader.readLine())!=null){
json+=temp;
}
return json;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}//网络请求数据

}

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐