网络请求框架
- HttpURLConnection(Sun)
- HttpClient((Android内置,6.0后移除))
- AsyncHttpClient
- xUtils
- OKHttp(Square)
- Volley(Google)
- Retrofit
- 获取网络状态
注:凡是向服务器提交数据用POST,凡是向服务器获取数据用GET
01-HttpURLConnection
//get方式
InputStream inputStream = newURL("http://www.baidu.com?username=zhangsan&age=23")
.openConnection()
.getInputStream();
//post方式
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);//设置允许给服务器提交数据流
connection.setRequestMethod("POST");
//获取对外输出流
OutputStream os = connection.getOutputStream();
os.write(("advice="+URLEncoder.encode(advice)+"&contact="+contact).getBytes());
/*
* 注意:一定顺序不要写错,先输出,在输入
*/
InputStream is = connection.getInputStream();
String is2Str = StreamUtils.is2Str(is);
02-AsyncHttpClient
//1. get
AsyncHttpClient client = new AsyncHttpClient();
/*
* 参数2:网络访问的监听
*/
client.get(path+"?advice="+URLEncoder.encode(advice)+"&contact="+contact, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("tag", "ThreadName="+Thread.currentThread().getName());
String string = new String(responseBody);
Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("tag", "ThreadName="+Thread.currentThread().getName());
Toast.makeText(MainActivity.this, "异常:"+error, Toast.LENGTH_SHORT).show();
}
});
//2. post
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("advice", advice);
params.put("contact", contact);
/*
* 参数2:post请求给服务器提交的参数
*/
client.post(path, params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("tag", "ThreadName="+Thread.currentThread().getName());
String string = new String(responseBody);
Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("tag", "ThreadName="+Thread.currentThread().getName());
Toast.makeText(MainActivity.this, "异常:"+error, Toast.LENGTH_SHORT).show();
}
});
03-xUtils
注:xUtils:国产的,扩展性不好,一般只用它的断点下载功能
/*
* 1. 创建一个核心类
*/
HttpUtils httpUtils = new HttpUtils();
File file = new File(Environment.getExternalStorageDirectory(), "b.mp3");
/*
* 参数1:网络文件的URL地址
* 参数2:要保存到本地的地址
* 参数3:是否支持断点续传
* 参数4:是否重命名
*/
httpHandler = httpUtils.download(path, file.getAbsolutePath(), true, false, new RequestCallBack<File>() {
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
Toast.makeText(MainActivity.this, "下载成功"+responseInfo.result.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(HttpException error, String msg) {
Toast.makeText(MainActivity.this, "error="+error+"/msg="+msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
Log.d("tag", "current="+current);
pb.setProgress((int) ((current*100/total)));
}
});
04-OKHttp(Square)
注:OKhttp的enqueue是在子线程中执行的,
1. get提交数据
public void get(View view) {
/*
* 1. 创建一个核心对象
*/
OkHttpClient okHttpClient = new OkHttpClient();
/*
* 3. 创建一个请求对象Request
*/
Request request = new Request.Builder()
.url("http://10.0.2.2:8080/helloWeb/CommentServlet?advice=张三&contact=123456")
.build();
/*
* 2. 让okHttpClient创建新的请求任务
*/
Call newCall = okHttpClient.newCall(request);
/*
* 4. 执行请求任务
*/
newCall.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("tag", "ThreadName=" + Thread.currentThread().getName());
// 获取状态码
int code = response.code();
Log.d("tag", "code=" + code);
// 获取服务器返回的数据
String result = response.body().string();
handler.obtainMessage(1, result).sendToTarget();
}
@Override
public void onFailure(Call call, IOException e) {
Log.d("tag", "ThreadName=" + Thread.currentThread().getName());
handler.obtainMessage(2, e).sendToTarget();
}
});
}
2. post提交数据
public void post(View view) {
//1
OkHttpClient okHttpClient = new OkHttpClient();
// Builder builder = new FormBody.Builder();
// builder.add("advice", "雨泽");
// builder.add("contact", "王五");
// FormBody formBody = builder.build();
RequestBody body = new FormBody.Builder()
.add("advice", "雨泽")
.add("contact", "王五")
.build();
// okhttp3.Request.Builder builder2 = new Request.Builder();
// builder2.url("http://10.0.2.2:8080/helloWeb/CommentServlet");
// builder2.post(formBody);
// Request request2 = builder2.build();
Request request = new Request.Builder()
.url("http://10.0.2.2:8080/helloWeb/CommentServlet")
.post(body)
.build();
//2
Call newCall = okHttpClient.newCall(request);
newCall.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("tag", "ThreadName=" + Thread.currentThread().getName());
// 获取状态码
int code = response.code();
Log.d("tag", "code=" + code);
// 获取服务器返回的数据
String result = response.body().string();
handler.obtainMessage(1, result).sendToTarget();
}
@Override
public void onFailure(Call call, IOException e) {
Log.d("tag", "ThreadName=" + Thread.currentThread().getName());
handler.obtainMessage(2, e).sendToTarget();
}
});
}
3. 文件上传(post)
public void upload(View view) {
//将本地sdcard中的sms.xml上传到服务器
OkHttpClient okHttpClient = new OkHttpClient();
//常见请求体对象,因为要文件上传,所有创建的是MultipartBody对象
RequestBody body = new MultipartBody.Builder()
/*
* 参数1:对应文件参数的name属性:相当于 : <input type="file" name="myfile"><br><br>
* 参数2:文件的名称,仅仅是名称
* 参数3:文件的类型 MediaType.parse("image/jpg")
* 参数4:真正要上传的文件
*/
.addFormDataPart("myfile", "sms.xml", RequestBody.create(MediaType.parse("*/*"), new File(Environment.getExternalStorageDirectory(), "sms.xml")))
.build();
//创建请求对象
Request request = new Request.Builder()
.url("http://10.0.2.2:8080/helloWeb/UploadServlet")
.post(body)
.build();
//创建一个新的请求任务
Call newCall = okHttpClient.newCall(request);
//执行任务
newCall.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("tag", "ThreadName=" + Thread.currentThread().getName());
// 获取状态码
int code = response.code();
Log.d("tag", "code=" + code);
// 获取服务器返回的数据
String result = response.body().string();
handler.obtainMessage(1, result).sendToTarget();
}
@Override
public void onFailure(Call call, IOException e) {
Log.d("tag", "ThreadName=" + Thread.currentThread().getName());
handler.obtainMessage(2, e).sendToTarget();
}
});
}
4. 文件下载(get)
public void download(View view) {
//http://localhost:8080/helloWeb/五环.mp4
/*
* 1. 创建核心类
*/
OkHttpClient okHttpClient = new OkHttpClient();
/*
* 3. 创建请求对象
*/
Request request = new Request.Builder()
.url("http://10.0.2.2:8080/helloWeb/fiveringnihao.mp4")
.build();
/*
* 2. 创建新的请求任务
*/
Call newCall = okHttpClient.newCall(request);
/*
* 4. 异步执行任务
*/
newCall.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.code()!=200) {
handler.obtainMessage(2,"状态码不正确:"+response.code()).sendToTarget();
return;
}
//将下载的文件保存到sdcard上
InputStream is = response.body().byteStream();
FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "fivering.mp4"));
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
fos.close();
is.close();
handler.obtainMessage(1, "下载完毕").sendToTarget();
}
@Override
public void onFailure(Call call, IOException e) {
Log.d("tag", "ThreadName=" + Thread.currentThread().getName());
handler.obtainMessage(2, e).sendToTarget();
}
});
}
08-获取网络状态
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//获取当前可用的网络,如果当前没有可用的网络,返回null
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo==null) {
tv_state.setText("当前没有可用的网络");
tv_state.setTextColor(Color.parseColor("#ff0000"));
}else {
//获取当前网络的名称"MOBILE","WIFI"
String typeName = activeNetworkInfo.getTypeName();
//如果是"MOBILE"类型网络,我们可以进一步获取4G(LET)或者3G
String subtypeName = activeNetworkInfo.getSubtypeName();
tv_state.setTextColor(Color.BLUE);
tv_state.setText("当前网络类型:"+typeName+"/"+subtypeName);
}