如何用网络请求数据呢?
第一步 创建一个工具类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 "";
}//网络请求数据
}
最后
以上就是醉熏小土豆最近收集整理的关于Android开发-使用工具类进行网络请求数据的全部内容,更多相关Android开发-使用工具类进行网络请求数据内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复