大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE稳定放心使用
Okhttp
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账号...