关于Android网络请求,是开发中遇到最多的问题之一,也是学习Android开发以来最晕的问题,于是重新梳理了一遍相关知识点,相关总结网上有很多,书上也都有,这里不再赘述。下面分享一个网络请求的封装工具类供大家交流学习
该工具类适合新手学习使用,仅仅实现了最基本的原生get、post网络请求,能满足最基本的网络请求需求,但是面对复杂的网络请求是不适合的,建议在学习完该工具类后学习Volley、OkHttp等工具类。
1. Get请求,返回数据(关键代码)
url = new URL(urlStr);
connection=(HttpURLConnection)url.openConnection();
//HttpURLConnection通用属性设置,TIMEOUT_IN_MILLIONS为int类型数据
connection.setConnectTimeout(TIMEOUT_IN_MILLIONS);
connection.setReadTimeout(TIMEOUT_IN_MILLIONS);
connection.setRequestMethod("GET");
connection.setRequestProperty("accept","*/*");
connection.setRequestProperty("connection","Keep-Alive");
//判断状态码是否为200,是则服务器端响应成功
if (connection.getResponseCode() == 200){
//读取返回的数据转换成字节流存入byte数组
is = connection.getInputStream();
bos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[128];
while ((len = is.read(buf)) != -1){
bos.write(buf,0,len);
}
bos.flush();
2. Post请求
String result="";
PrintWriter out = null;
InputStream in = null;
URL url=new URL(urlStr);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
//设置属性
connection.setRequestMethod("POST");
connection.setConnectTimeout(TIMEOUT_IN_MILLIONS);
connection.setReadTimeout(TIMEOUT_IN_MILLIONS);
connection.setRequestProperty("charset",CHARSET);
connection.setRequestProperty("connection","Keep-Alive");
connection.setRequestProperty("accept","*/*");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
if (params != null && params.trim().equals("")){
out = new PrintWriter(connection.getOutputStream());//获取输入流
out.print(params);//发送请求参数
out.flush();//flush输出流的缓冲
}
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine())!=null){
result += line;
}
其实get和post方法是很相似的,post可以说实在get的基础上增加了PrintWriter的使用,另外这里都只是关键代码,需要注意两点:
1. try/catch的使用
2. inputStream、HttpURLConnection等使用完记得关闭释放资源
3. 工具类的使用
HttpUtil的使用:
1. 不要在主线程中进行UI更新,建议使用Handler或者其他异步方法
2. 新手注意,在成功进行网络请求后,正确进行JSON或者XML数据解析,这里建议使用GSON进行解析
这里以一个简单的get使用实例来说明HttpUtil工具类的使用,因为这里我获取到的JSON数据格式只有{},因此只用到JsonObject,代码如下:
1. 开启一个线程,并使用Hadnler发送并更新ui
new Thread(new Runnable() {
@Override
public void run() {
String result = HttpUtil.doGet(Content.url);
Log.d("MyTAG",result);
try {
if (result!=null) {
JSONObject jsonObject = new JSONObject(result);
name = jsonObject.getString("img");
handler.sendEmptyMessage(1);
}else {
handler.sendEmptyMessage(0);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
}
2. 使用Handler接收
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, "handleMessage", Toast.LENGTH_SHORT).show();
switch (msg.what){
case 1:
txt.setText(name);
break;
case 0:
txt.setText("EmptyMessage!");
break;
}
}
};
可以把开启的Thread封装成一个方法在onCreate()中调用。