java 中OkHttp的使用方法及实例
概述
准备研究Retrofit,而它是依赖OkHttp的,所以先使用一下OkHttp,不深究源码,只探究使用方法。以后有机会再翻查源码。
在进行之前,首先需要2个jar包,其中一个是okHttp的jar包,github上可以下载,另一个是它的依赖包,这个很关键,没有它,项目就无法运行。
OkHttp请求的2种方式
不难猜测,涉及到网络请求,那么无非2种方式,一种是使用回调,另一种则是开启子线程执行。
第一种:开启子线程执行
|
1
2
3
4
5
6
7
8
9
10
11
12
|
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder().url(url).build();
try {
<span style="white-space:pre"> </span>Response execute = client.newCall(build).execute();
if(execute.isSuccessful()){
System.out.println("wisely aaa");
} else {
System.out.println("wisely bbb");
}
} catch (IOException e) {
e.printStackTrace();
}
|
第二种:使用回调,我个人最喜欢使用这种。(PS:觉得自己真是too young too simple!!本来以为回调的方法是在主线程,结果发现,竟然是子线程,子线程….)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder().url(url).build();
client.newCall(build).enqueue(new Callback() {
@Override
public void onResponse(Response arg0) throws IOException {
System.out.println("wisely success");
}
@Override
public void onFailure(Request arg0, IOException arg1) {
System.out.println("wisely failure");
}
});
|
OkHttp之get请求
1、获取图片
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder().url(url).build();
client.newCall(build).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
// byte[] bytes = response.body().bytes();
InputStream is = response.body().byteStream();
Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
// Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,options);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
Message msg = handler.obtainMessage();
msg.obj = bitmap;
handler.sendMessage(msg);
}
@Override
public void onFailure(Request arg0, IOException arg1) {
System.out.println("wisely fail:"+arg1.getCause().getMessage());
}
});
|
只写了关键代码,并未写handler的相关代码。
获取网络图片有2种方式,1是获取byte数组,2是获取输入流。注意,onResponse在子线程中…
OkHttp之post请求
比起get请求,post请求的分类略多。
1、首先是最常用的表单提交。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormEncodingBuilder()
.add("userName", "13363114390")
.add("password", "200820e3227815ed1756a6b531e7e0d2").build();
Request build = new Request.Builder().url(url).post(body).build();
client.newCall(build).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
String lenght = response.header("Content-Length");
System.out.println("wisely--lenght:" + lenght);
LoginResponse loginResponse = new Gson().fromJson(response.body().charStream(), LoginResponse.class);
System.out.println("wisely---" + loginResponse.getMessage());
}
@Override
public void onFailure(Request arg0, IOException arg1) {
System.out.println("wisely-----fail");
}
});
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
String tokeId;
boolean result;
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTokeId() {
return tokeId;
}
public void setTokeId(String tokeId) {
this.tokeId = tokeId;
}
}
|
上面的是一个简单的登录表单的提交,其中将返回的json数据封装到了一个bean中。除了能够获取json数据外,还能获取到各个消息头。
2、上传图片
这是我最关心的一个功能,实验证明,okHttp上传图片的功能确实强大,支持多图片上传。
|
1
|
private MediaType PNG = MediaType.parse("application/octet-stream");
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
OkHttpClient client = new OkHttpClient();
RequestBody body = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(Headers.of("Content-Disposition","form-data; name=\\"files\\";filename=\\"img1.jpg\\""),RequestBody.create(PNG, file1))
.addPart(Headers.of("Content-Disposition","form-data; name=\\"files\\";filename=\\"img2.jpg\\""),RequestBody.create(PNG, file2)).build();
Request request = new Request.Builder()
<span style="white-space:pre"> </span>.url(url)
.post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
if(response.isSuccessful()){
UploadPNGResponse uploadPNGResponse = new Gson().fromJson(response.body().charStream(), UploadPNGResponse.class);
String msg = uploadPNGResponse.getMsg();
List<String> list = uploadPNGResponse.getList();
for (String string : list) {
System.out.println("wisely---path:"+string);
}
}
}
@Override
public void onFailure(Request arg0, IOException arg1) {
System.out.println("wisely---fail--"+arg1.getCause().getMessage());
}
});
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class UploadPNGResponse{
String msg;
boolean result;
List<String> list;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/u013673799/article/details/49865927
相关文章
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-25 44
-
JAVA中通过Hibernate-Validation进行参数验证
2025-05-29 49 -
2025-05-27 32
-
2025-05-29 99
-
2025-05-25 105

