Android学习笔记(十九) OkHttp
一、概述
根据我的理解,OkHttp是为了方便访问网络或者获取服务器的资源,而封装出来的一个工具包。通常的使用步骤是:首先初始化一个OkHttpClient对象,然后使用builder模式构造一个Request,之后使用Call来执行这个Request。其中,OkHttpClient一般只使用一个,而OkHttpClient的newCall方法则对应每次请求的执行。
二、Get
2.1 步骤分解
- 拿到OkHttpClient对象
- 构造Request
- 将Request封装为Call
- 执行Call(直接execute或者enqueue)
2.2 程序
public void doGet(View view) throws IOException{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://www.imooc.com/").build();
Call call = client.newCall(request);
call.enqueue(new Callback(){ @Override
public void onFailure(Call call, IOException e) {
Log.e("okHttp",e.getMessage());
} @Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("okHttp","doGet success!");
String string = response.body().string();
Log.d("okHttp Content",string);
} });
}
上面的enqueue也可以换成execute,不过执行后返回一个Response对象。
相应代码替换成:
Response response = call.execute();
if(response.isSuccessful){
return response.body().string();
}else{
throw new IOException("Unexpected code " + response);
}
三、Post键值对
3.1 步骤分解
- 拿到OkHttpClient对象
- 构造RequestBody
- 构造Request
- 将Request封装为Call
- 执行Call
3.2 代码
public void doPost(View view){
OkHttpClient client = new OkHttpClient(); RequestBody body = new FormBody.Builder().builder()
.add("username","admin")
.add("password","123")
.build();
Request.Builder builder = new Request.Builder();
Request = builder.url(mBaseUrl+"login").post(body).build(); Call call = client.newCall(request);
call.enqueue(new Callback(){ @Override
public void onFailure(Call call, IOException e) {
Log.e("okHttp",e.getMessage());
} @Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("okHttp","doGet success!");
String string = response.body().string();
Log.d("okHttp Content",string);
} });
}
Call那个步骤在多数程序中都会用到,所以最好是抽取成为一个函数。在服务器端使用的是struts2架构,因此需要添加一个action,在所需调用的函数中将username和password打印出来就能看到post上去的数据了。
四、Post JSON(字符串)
和上面的步骤唯一不同的是RequestBody的构造。这里使用的是RequestBody的静态方法create()。
RequestBody body = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"),"{username:admin,password:123}");
在服务器端的函数代码为:
public String postString(){
HttpServletRequest request = ServletActionContext.getRequest();
ServletInputStream is = request.getInputStream(); StringBuilder sb = new StringBuilder();
int len = 0;
byte[] buf = new byte[1024]; while((len = is.read(buf)) != -1){
sb.append(new String(buf, 0, len));
} System.out.println(sb.toString()); return null;
}
五、Post File
参考上面的代码,这里构造RequestBody也是调用它的静态方法create(),只不过参数改成了跟File相适应的。
重复代码已省去。至于MediaType参数,参考http://www.w3school.com.cn/media/media_mimeref.asp。
File file = new File(Environment.getExternalStorageDirectory(),"test.jpg");
if(!file.exists()){
Log.e("file error","not exist!");
return;
}
RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"),file);
服务器端的程序也和上面的程序大同小异,只不过改成用FileOutputStream来接受InputStream里面的数据,而不是上面的StringBuilder。
public String postFile(){
HttpServletRequest request = ServletActionContext.getRequest();
ServletInputStream is = request.getInputStream(); String dir
= ServletActionContext.getServletContext().getRealPath("files"
);
File file = new File(dir,"test.jpg");
FileOutputStream fos = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024]; while((len = is.read(buf)) != -1){
fos.write(buf, 0, len);
} fos.flush();
fos.close(); return null;
}
这里有个需要注意的地方,getRealPath得到的路径默认是tomcat下webapps中的项目文件夹下。因为每次重启服务器里面的文件都会被删除,所以我更改了路径:
<Context path="/VCloud" docBase="D:\Workspace\VCloudDir" debug="0" reloadable="true"/>
我把文件test.jpg放在D:\Workspace\VCloudDir\files下,然后在浏览器中输入localhost:8080/VCloud/files/test.jpg就能打开这个文件。
六、上传文件以及参数
使用MultipartBody的意义在于:传输文件的同时可以传输字段;可以指定文件名;可以一次上传多个文件。
代码仅展示RequestBody部分,其他部分和上面基本一致。
File file = new File(Environment.getExternalStorageDirectory(),"test.jpg");
RequestBody fileRequestBody = RequestBody.create(MediaType.parse("application/octet-stream"),file);
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
RequestBody body = multipartBuilder
.type(MultipartBody.FORM)
.addFormDataPart("username","admin")
.addFormDataPart("password","123")
.addFormDataPart("mPhoto","test.jpg",fileRequestBody)
.build();
服务端部分:
public File mPhoto;
public String mPhotoFileName;//注意写法是固定的
public String uploadInfo(){ if(mPhoto == null){
System.out.println(mPhotoFileName + " is null .);
} String dir = ServletActionContext.getServletContext().getRealPath("files"); File file = new File(dir, mPhotoFileName);
FileUtils.copyFile(mPhoto, file); return null;
}
七、下载文件
和get方法类似,不同之处在于对得到的Response的处理,即onResponse里面的内容。
url就是文件地址,如localhost:8080/VCloud/files/test.jpg。
public void onResponse(Response response){
Log.d("onResponse","onResponse"); InputStream is = response.body().byteStream();
int len = 0;
File file = new File(Environment.getExternalStorageDirectory(),"test.jpg");
byte[] buf = new byte[128];
FileOutputStream fos = new FileOutputStream(file); while((len = is.read(buf)) != -1){
fos.write(buf, 0, len);
} fos.flush();
fos.close();
is.close(); Log.d("download","download success!");
}
Android学习笔记(十九) OkHttp的更多相关文章
- python3.4学习笔记(十九) 同一台机器同时安装 python2.7 和 python3.4的解决方法
python3.4学习笔记(十九) 同一台机器同时安装 python2.7 和 python3.4的解决方法 同一台机器同时安装 python2.7 和 python3.4不会冲突.安装在不同目录,然 ...
- 【转】Pro Android学习笔记(九八):BroadcastReceiver(2):接收器触发通知
文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.sina.com.cn/flowingflying或作者@恺风Wei-傻瓜与非傻瓜 广播接 ...
- 【转】 Pro Android学习笔记(九二):AsyncTask(1):AsyncTask类
文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.csdn.net/flowingflying/ 在Handler的学习系列中,学习了如何h ...
- Android学习笔记(九)——布局和控件的自定义
//此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! View是 Android中一种最基本的 UI组件,它可以在屏幕上绘制一块矩形区域,并能响应这块区域的各种事件 ...
- (C/C++学习笔记) 十九. 模板
十九. 模板 ● 模板的基本概念 模板(template) 函数模板:可以用来创建一个通用功能的函数,以支持多种不同形参,进一步简化重载函数的函数体设计. 语法: template <<模 ...
- 【转】 Pro Android学习笔记(九四):AsyncTask(3):ProgressDialog
文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.csdn.net/flowingflying/ Progress Dialog小例子 我们 ...
- 【转】 Pro Android学习笔记(九三):AsyncTask(2):小例子
目录(?)[-] 继承AsyncTask UI操作接口 使用AsyncTask 文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.csdn. ...
- Android学习笔记(九) 视图的应用布局效果
最近少了写博客,可能最近忙吧,工作上忙,因为工作原因也忙于学习,也没记录什么了,也没有按照之前的计划去学习了.现在就记录一下最近学到的. 要做Android应用,界面设计少不了,可惜之前一直在用Win ...
- 【转】 Pro Android学习笔记(九一):了解Handler(5):组件生命
文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件.转载须注明出处:http://blog.csdn.net/flowingflying/ 对于activity,消息是在OnCrea ...
- 【转】Pro Android学习笔记(九):了解Content Provider(下下)
Content provider作为信息的读出,比较常见的还有文件的读写,最基础的就是二进制文件的的读写,例如img文件,音频文件的读写.在数据库中存放了该文件的路径,我们可以通过ContentPro ...
随机推荐
- WinDbg设置托管进程断点
WinDbg的Live模式调试..Net 托管代码 ,使用bp,bu,bm无法设置断点,也许是我不会.研究了下,托管代码有自己的命令,!BPMD 模块名 完全限定的方法名 步骤: 1.查找进程PID, ...
- 书写优雅的shell脚本(六)- shell中的命令组合(&&、||、())
shell 在执行某个命令的时候,会返回一个返回值,该返回值保存在 shell 变量 $? 中.当 $? == 0 时,表示执行成功:当 $? == 1 时,表示执行失败. 有时候,下一条命令依赖前 ...
- data对象转化成后端需要的json格式
data=JSON.stringify(json_data); $.ajax({type:'post',url:url+'warehouse/create_alliance_out/',data:da ...
- bzoj 1098 办公楼biu —— 链表+栈
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1098 首先,没有连边的人一定得在一个连通块里: 先把所有人连成一个链表,然后从第一个人开始, ...
- 监听屏幕旋转事件window. onorientationchange
// 判断屏幕是否旋转 function orientationChange() { switch(window.orientation) { case 0: alert("肖像模式 0,s ...
- springmvc不进入Controller导致404
转自:https://blog.csdn.net/qq_36769100/article/details/71746449#1.%E5%90%AF%E5%8A%A8%E9%A1%B9%E7%9B%AE ...
- 012--python字符编码和list列表和循环语句
一.字符编码: ASCII码最多只能表示 256个符号,每一个字符占8位 为什么一个字节占8位?因为计算机在读一串二进制数111011001111101110的时候, 要按照规定的长度截取,才能分清一 ...
- linux中使用netstat
1 功能: 显示本机的网络连接.运行端口和路由表的信息. 2 常见选项 -a:显示本机所有连接和监听的端口 -n:网络IP地址的形式显示当前建立的有效连接和端口 -r:显示路由表信息 -s:显示按协议 ...
- python学习笔记1-基础语法
1 在3版本中print需要加上括号2 多行语句:用\连接 item_one=1 item_two=2 item_three=3 total = item_one + \ item_two + \ i ...
- Redis高级
Redis高级 redis数据备份与恢复 Redis SAVE 命令用于创建当前数据库的备份. redis Save 命令基本语法如下: redis 127.0.0.1:6379> SAVE 实 ...