Okhttp学习及封装

Okhttp学习及封装Okhttp1.学习Okhttp2.OkHttp的封装1.学习Okhttp需要导入依赖implementation’com.squareup.okhttp3:okhttp:3.12.1’四个按钮需要写入布局get请求,post请求,下载文件,上传文件别忘了加入SD卡权限,网络权限privatevoidinitView(){get=(Button)…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

1.学习Okhttp

需要导入依赖

 implementation 'com.squareup.okhttp3:okhttp:3.12.1'

四个按钮需要写入布局
get请求,post请求,下载文件,上传文件
别忘了加入SD卡权限,网络权限

  private void initView() { 

get = (Button) findViewById(R.id.get);
post = (Button) findViewById(R.id.post);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
get.setOnClickListener(new View.OnClickListener() { 

@Override
public void onClick(View v) { 

OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() { 

@Override
public void onFailure(Call call, final IOException e) { 

handler.post(new Runnable() { 

@Override
public void run() { 

Toast.makeText(MainActivity.this, e.getMessage() + "", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException { 

final String string = response.body().string();
handler.post(new Runnable() { 

@Override
public void run() { 

Toast.makeText(MainActivity.this, string + "", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
post.setOnClickListener(new View.OnClickListener() { 

@Override
public void onClick(View v) { 

OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS)
.build();
FormBody formBody = new FormBody.Builder()
.add("page", "1")
.build();
Request request = new Request.Builder()
.url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&")
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() { 

@Override
public void onFailure(Call call, final IOException e) { 

handler.post(new Runnable() { 

@Override
public void run() { 

Toast.makeText(MainActivity.this, e.getMessage() + "", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException { 

final String string = response.body().string();
handler.post(new Runnable() { 

@Override
public void run() { 

Toast.makeText(MainActivity.this, string + "", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
download = (Button) findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() { 

@Override
public void onClick(View v) { 

OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url("http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() { 

@Override
public void onFailure(Call call, final IOException e) { 

handler.post(new Runnable() { 

@Override
public void run() { 

Toast.makeText(MainActivity.this, e.getMessage() + "", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException { 

ResponseBody body = response.body();
maxlen = body.contentLength();
InputStream is = body.byteStream();
File file = Environment.getExternalStorageDirectory();
FileOutputStream fos = new FileOutputStream(new File(file, "猩猩.mp4"));
int len = 0;
byte[] b = new byte[1024];
long carlen = 0;
while ((len = is.read(b)) != -1) { 

fos.write(b, 0, len);
carlen += len;
int progress = (int) (carlen * 100 / maxlen);
progressBar.setProgress(progress);
}
}
});
}
});
Upload = (Button) findViewById(R.id.Upload);
Upload.setOnClickListener(new View.OnClickListener() { 

@Override
public void onClick(View v) { 

OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS)
.build();
File file = Environment.getExternalStorageDirectory();
RequestBody requestBody = RequestBody.create(MediaType.parse("media/mp4"), new File(file, "猩猩.mp4"));
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file","xingxing.mp4",requestBody)
.build();
Request request = new Request.Builder()
.url("http://169.254.141.30/hfs/")
.post(multipartBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() { 

@Override
public void onFailure(Call call, final IOException e) { 

handler.post(new Runnable() { 

@Override
public void run() { 

Toast.makeText(MainActivity.this, e.getMessage() + "", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException { 

handler.post(new Runnable() { 

@Override
public void run() { 

Toast.makeText(MainActivity.this,   "上传成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
}

2.OkHttp的封装

代码之路很艰辛,依照上面的方法我们不能重复写的代码
可一给他封装一个工具类
我们用到了单利模式
主类直接调用就行

   private OkHttpClient client;
private Handler handler=new Handler();
private MyOkUtiles() { 

client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
}
private static MyOkUtiles myOkUtiles=null;
public static MyOkUtiles getInstance(){ 

if (myOkUtiles==null){ 

synchronized (Object.class){ 

if (myOkUtiles==null){ 

myOkUtiles=new MyOkUtiles();
}
}
}
return myOkUtiles;
}
public void get(String url, final MyOkListener myOkListener){ 

Request request = new Request.Builder()
.url(url)
.get().build();
client.newCall(request).enqueue(new Callback() { 

@Override
public void onFailure(Call call, IOException e) { 

final String message = e.getMessage();
handler.post(new Runnable() { 

@Override
public void run() { 

myOkListener.MyError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException { 

final String string = response.body().string();
handler.post(new Runnable() { 

@Override
public void run() { 

myOkListener.MyOk(string);
}
});
}
});
}
public void post(String url, HashMap<String,String> map, final MyOkListener myOkListener){ 

FormBody.Builder builder = new FormBody.Builder();
HashMap<String, String> maps = new HashMap<>();
Set<Map.Entry<String, String>> entries = maps.entrySet();
for (Map.Entry<String, String> entry : entries) { 

builder.add(entry.getKey(),entry.getValue());
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
client.newCall(request).enqueue(new Callback() { 

@Override
public void onFailure(Call call, IOException e) { 

final String message = e.getMessage();
handler.post(new Runnable() { 

@Override
public void run() { 

myOkListener.MyError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException { 

final String string = response.body().string();
handler.post(new Runnable() { 

@Override
public void run() { 

myOkListener.MyOk(string);
}
});
}
});
}
public void download(String url, final String path, final MyProgressListener myProgressListener){ 

Request request = new Request.Builder()
.url(url)
.get().build();
client.newCall(request).enqueue(new Callback() { 

@Override
public void onFailure(Call call, IOException e) { 

final String message = e.getMessage();
handler.post(new Runnable() { 

@Override
public void run() { 

myProgressListener.MyError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException { 

ResponseBody body = response.body();
final long maxLen = body.contentLength();
InputStream is = body.byteStream();
FileOutputStream fos = new FileOutputStream(path);
int len=0;
byte[] b = new byte[1024];
long carlen=0;
while ((len=is.read(b))!=-1){ 

fos.write(b,0,len);
carlen+=len;
final int progress= (int) (carlen*100/maxLen);
handler.post(new Runnable() { 

@Override
public void run() { 

myProgressListener.Progress(progress);
}
});
}
handler.post(new Runnable() { 

@Override
public void run() { 

myProgressListener.Finish();
}
});
}
});
}
public void upload(String url, String path, String servername, String type, final MyOkListener myOkListener){ 

RequestBody requestBody = RequestBody.create(MediaType.parse(type), new File(path));
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", servername, requestBody)
.build();
Request request = new Request.Builder()
.url(url)
.post(multipartBody)
.build();
client.newCall(request).enqueue(new Callback() { 

@Override
public void onFailure(Call call, IOException e) { 

final String message = e.getMessage();
handler.post(new Runnable() { 

@Override
public void run() { 

myOkListener.MyError(message);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException { 

if (response.isSuccessful()) { 

handler.post(new Runnable() { 

@Override
public void run() { 

myOkListener.MyOk("成功");
}
});
}else { 

handler.post(new Runnable() { 

@Override
public void run() { 

myOkListener.MyOk("失败");
}
});
}
}
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/180465.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 利用原生JavaScript获取样式的方式小结

    利用原生JavaScript获取样式的方式小结

  • java面试时怎么做自我介绍_面试时如何做好自我介绍「建议收藏」

    java面试时怎么做自我介绍_面试时如何做好自我介绍「建议收藏」该楼层疑似违规已被系统折叠隐藏此楼查看此楼要想让人力资源考官们欣赏你,你必须明确地告诉考官们你具有应考职位必需的能力与素质,而只有您对此有信心并表现出这种信心后,你才证明了自己。所以我们要充满自信的自我介绍,那面试时如何做自我介绍,敬请阅读下文,或许下文有您想要的答案!.1、自我介绍切忌话多。.比如说,有的面试要求每个人用三句话介绍自己,难道真的只能姓名+专业+学校了?求职者遇到这种情况,当然…

  • 图形界面JAVA_aardio plus

    图形界面JAVA_aardio plus前阵子在用python写一些小程序,写完后就开始思考怎么给python程序配一个图形界面,毕竟控制台实在太丑陋了。于是百度了下python的图形界面库,眼花缭乱的一整页,拣了几件有“特色”有“噱头”的下载下来做了个demo,仍旧不是很满意,不是下载安装繁琐,就是界面丑陋或者难写难用,文档不齐全。后来那天,整理电脑文件发现了6年前下载的aatuo(现已更名aardio),顿时一阵惊喜。先说说aard…

    2022年10月23日
  • 使用pycharm安装包失败后,应该怎么办?

    使用pycharm安装包失败后,应该怎么办?用pycharm进行安装第三方包的时候,一些情况下会出现安装失败(具体怎么安装搜一下,教程很全,但这不是想说的重点)。有时候是因为pip版本较低,升级一下即可,但有时候就是安装不上,原因查了一下,有的博主说是pip不支持断点续传,也有的说是版本路径问题。但是不论如何,这个问题有解决的方法,也是迫不得已的办法。第一步:去官网下载对应的安装包,网址如下:这是网址至于应该安装什么样的包,最简单…

  • C#调用windows api示例

    这是运行结果:Api函数是构筑Windws应用程序的基石,每一种Windows应用程序开发工具,它提 供的底层函数都间接或直接地调用了Windows API函数,同时为了实现功能

    2021年12月21日
  • .ipynb与.py文件快速互转[通俗易懂]

    .ipynb与.py文件快速互转[通俗易懂].ipynb代码转为.py:法一:在xxx.ipynb所在目录下,打开终端,并输入命令:jupyternbconvert–toscriptxxx.ipynb其中xxx.ipynb是要转换文件的名字,转换后在该目录下出现xxx.py文件(有的版本是xxx.txt文件,再改下后缀即可)。法二:在Jupyternotebook或GoogleColab中打开ipynb文件,然后选择file–downloadas–pythonfile.py代码转为.ipynb:

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号