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();
}
});
}
});
}
}