Okhttp基本操作
使用okhttp完成的登录、注册、上传和下载
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button get;
private Button register;
private Button login;
private ProgressBar bar;
private Button upload;
private Button download;
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if(msg.what == 101){
int progress = (int) msg.obj;
bar.setProgress(progress);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 101);
}
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
bar = (ProgressBar) findViewById(R.id.bar);
get = (Button) findViewById(R.id.get);
upload = (Button) findViewById(R.id.upload);
download = (Button) findViewById(R.id.download);
register = (Button) findViewById(R.id.register);
login = (Button) findViewById(R.id.login);
get.setOnClickListener(this);
register.setOnClickListener(this);
login.setOnClickListener(this);
upload.setOnClickListener(this);
download.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.get:
get();
break;
case R.id.register:
register();
break;
case R.id.login:
login();
break;
case R.id.upload:
upload();
break;
case R.id.download:
download();
break;
}
}
private void download() {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url("http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4")//视频url
.get()
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
String message = e.getMessage();
Toast.makeText(MainActivity.this, ""+message, Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
long max = body.contentLength();//总大小
InputStream inputStream = body.byteStream();//字节流
FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/Download/xingxing.mp4");
byte[] bytes = new byte[1024];
int len = 0;
int count = 0;//下载大小
while ((len = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
count+=len;
int progress = (int) (count*100/max);//进度0-100
Message obtain = Message.obtain();
obtain.what = 101;
obtain.obj = progress;
handler.sendMessage(obtain);
}
}
});
}
private void upload() {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.build();
// MultipartBody请求体
RequestBody requestBody = RequestBody.create(MediaType.parse("video/mp4"),new File("/sdcard/Movies/houzi.mp4"));
// RequestBody requestBody2 = RequestBody.create(MediaType.parse("image/jpg"),new File("/sdcard/DCIM/Camera/55.jpg"));
//
// RequestBody requestBody3 = RequestBody.create(MediaType.parse("image/jpg"),new File("/sdcard/DCIM/Camera/haha.jpg"));
//
// RequestBody requestBody4 = RequestBody.create(MediaType.parse("video/mp4"),new File("/sdcard/Download/xingxing.mp4"));
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)//设置方式
//参数一:"file" 参数二 :上传到服务器的名字 参数三:数据
.addFormDataPart("file","1.mp4",requestBody)//添加提交的文件数据
//多文件上传
// .addFormDataPart("file","1.jpg",requestBody2)
// .addFormDataPart("file","2.jpg",requestBody3)
// .addFormDataPart("file","2.mp4",requestBody4)
.build();
Request request = new Request.Builder()
.url("http://192.168.1.5:8080/Upload/UpServlet")
.post(multipartBody)//请求体 MultipartBody
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
String message = e.getMessage();
Log.d("---", "onFailure: "+message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
Log.d("---", "onResponse: "+json);
}
});
}
//post请求登录 通过form表单提交
private void login() {
//TODO 1:client客户端
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)//60秒
.readTimeout(60 * 1000, TimeUnit.MILLISECONDS)//60秒
.writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)//60秒
// .callTimeout() 千万不要写
.build();
//TODO 请求体 form表单提交 username,password,repassword
FormBody formBody = new FormBody.Builder()
.add("username","zhaoxuhui111111")
.add("password","123456")
.build();
//TODO 2:request请求
Request request = new Request.Builder()
.url("https://www.wanandroid.com/user/login")
.post(formBody)//post请求需要设置请求体
.build();
//TODO 3:client发起request---》call连接
Call call = client.newCall(request);
//TODO 4:加入队列中(线程池)---》response
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {//失败
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "失败:" + message, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {//成功
//ResponseBody 响应体
ResponseBody body = response.body();
final String string = body.string();//千万不要tostring
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "" + string, Toast.LENGTH_SHORT).show();
}
});
}
});
}
//post请求注册
private void register() {
//TODO 1:client客户端
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)//60秒
.readTimeout(60 * 1000, TimeUnit.MILLISECONDS)//60秒
.writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)//60秒
// .callTimeout() 千万不要写
.build();
//TODO 请求体 form表单提交 username,password,repassword
FormBody formBody = new FormBody.Builder()
.add("username","zhaoxuhui111111")
.add("password","123456")
.add("repassword","123456")
.build();
//TODO 2:request请求
Request request = new Request.Builder()
.url("https://www.wanandroid.com/user/register")
.post(formBody)//post请求需要设置请求体
.build();
//TODO 3:client发起request---》call连接
Call call = client.newCall(request);
//TODO 4:加入队列中(线程池)---》response
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {//失败
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "失败:" + message, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {//成功
//ResponseBody 响应体
ResponseBody body = response.body();
final String string = body.string();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "" + string, Toast.LENGTH_SHORT).show();
}
});
}
});
}
//请求数据
private void get() {
//TODO 1:client客户端
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)//60秒
.readTimeout(60 * 1000, TimeUnit.MILLISECONDS)//60秒
.writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)//60秒
// .callTimeout() 千万不要写
.build();
//TODO 2:request请求
Request request = new Request.Builder()
.url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1")
.get()//请求方式
.build();
//TODO 3:client发起request---》call连接
Call call = client.newCall(request);
//TODO 4:加入队列中(线程池)---》response
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {//失败
final String message = e.getMessage();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "失败:" + message, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {//成功
//ResponseBody 响应体
ResponseBody body = response.body();
final String string = body.string();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "" + string, Toast.LENGTH_SHORT).show();
}
});
}
});
}
}