OkHttp的使用
package com.example.day30;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;
import android.widget.ProgressBar;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class MainActivity extends AppCompatActivity {
private String get="http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&itemid=2&act=ad_app";
private String post="http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&";
private static final String TAG = "123321";
private ProgressBar pb;
private InputStream is;
@SuppressLint("HandlerLeak")
private Handler han=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if( msg.what==222){
pb.setMax(Integer.parseInt(msg.obj.toString()));
}else {
int arg1 = msg.arg1;
pb.setProgress(arg1);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},222);
pb=findViewById(R.id.main_progress);
pb.setMax(100);
}
public void click(View view) {
switch (view.getId()) {
case R.id.main_button_get:
get();
break;
case R.id.main_button_post:
post();
break;
case R.id.main_button_downLoad:
load();
break;
case R.id.main_button_upLoad:
upload();
break;
}
}
private void upload() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpClient client = builder.readTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS).build();
Request.Builder builder1 = new Request.Builder();
MultipartBody file = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", "szf.png",
RequestBody.create(MediaType.parse("image/png"),
new File("/mnt/sdcard/Pictures/0w6d57.png"))).build();
Request request = builder1.url("http://169.254.112.25/hfs/")
.post(file)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: "+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "onResponse: 传输完成。");
}
});
}
private void load() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpClient client = builder.connectTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS)
.build();
Request.Builder builder1 = new Request.Builder();
Request request = builder1.url("http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4")
.get().build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: "+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
long l = body.contentLength();
Message mess = new Message();
mess.what=222;
mess.obj=l;
han.sendMessage(mess);
is = body.byteStream();
FileOutputStream fos = null;
try {
fos = new FileOutputStream("/mnt/sdcard/Movies/a12.mp4");
int len=0;
byte[] arr=new byte[1024];
int nlen=0;
while( (len=is.read(arr))!=-1){
nlen+=len;
Message mes = new Message();
mes.what=111;
mes.arg1=nlen;
han.sendMessage(mes);
fos.write(arr,0,len);
}
Log.i(TAG, "onRequestPermissionsResult: "+"下载完毕。");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if( requestCode==222&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
}
}
private void post() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpClient client = builder.readTimeout(1, TimeUnit.MINUTES).connectTimeout(1, TimeUnit.MINUTES)
.build();
Request.Builder builder1 = new Request.Builder();
FormBody.Builder formBody = new FormBody.Builder();
FormBody formBody1 = formBody.add("itemid", "2").add("act", "ad_app")
.build();
Request request = builder1.url(post).post(formBody1).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: "+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
String string = body.string();
Log.i(TAG, "post:onResponse: "+string);
}
});
}
private void get() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(1, TimeUnit.MINUTES);
builder.connectTimeout(1,TimeUnit.MINUTES);
OkHttpClient client = builder.build();
Request.Builder builder1 = new Request.Builder();
builder1.url(get);
builder1.get();
Request request = builder1.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: "+e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
String string = body.string();
Log.i(TAG, "onResponse: string:"+string);
}
});
}
}
对应的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="get请求"
android:id="@+id/main_button_get"
android:onClick="click"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="post请求"
android:id="@+id/main_button_post"
android:onClick="click"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下载"
android:id="@+id/main_button_downLoad"
android:onClick="click"
/>
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:id="@+id/main_progress"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="上传"
android:id="@+id/main_button_upLoad"
android:onClick="click"
/>
</LinearLayout>