请求文本数据
public static String getJson(String urlString) {
try {
URL url = new URL(urlString);
//获取网络连接对象
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
//得到请求结果码
int responseCode = httpConnection.getResponseCode();
//200为访问成功,300重定向,400客户端错误,500服务器错误
if (responseCode == 200) {
//读取网络数据
InputStream inputStream = httpConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String readLine = "";
String str = "";
while ((readLine = reader.readLine()) != null) {
str += readLine;
}
return str;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
请求图片
try {
URL url = new URL(urlBitmap);
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode==200){
InputStream inputStream = urlConnection.getInputStream();
//读取地址图片,获取位图工厂
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
外部工具类,调用即可
注意:
- 网络权限
<uses-permission android:name="android.permission.INTERNET" />
- 请求方法必须在子线程中,不然没数据