使用URLConnection做网络请求。
网络请求需要添加权限:uses-permission android:name=”android.permission.INTERNET”
//1.获取一个URL对象
URL url = new URL(url_str);
//2.通过URL对象得到一个HttpURLConnection对象
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
//3.设置HttpUrlConnection的一些参数,如:连接的超时时间,请求方式
openConnection.setRequestMethod("GET");//设置连接的请求方式,类型一定要大写
openConnection.setConnectTimeout(10*1000);//设置连接的超时时间
//4.获取服务器响应的状态码,并判断
int code = openConnection.getResponseCode();
if(code == 200){//200 成功 206 请求部分资源成功 300 跳转 400 失败 500 服务器异常
//5.得到连接的读取流,获取服务返回的内容。
InputStream inputStream = openConnection.getInputStream();
String result = StreamUtils.streamToString(inputStream);
//6.关闭链接 关闭流
openConnection.disconnect();
inputStream.close();