Okhttp基本操作

编程入门 行业动态 更新时间:2024-10-19 16:26:31

Okhttp基本<a href=https://www.elefans.com/category/jswz/34/1770947.html style=操作"/>

Okhttp基本操作

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(){@Overridepublic void handleMessage(@NonNull Message msg) {super.handleMessage(msg);if(msg.what == 101){int progress = (int) msg.obj;bar.setProgress(progress);}}};@Overrideprotected 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);}@Overridepublic 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(".mp4")//视频url.get().build();client.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {String message = e.getMessage();Toast.makeText(MainActivity.this, ""+message, Toast.LENGTH_SHORT).show();}@Overridepublic 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-100Message 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() {@Overridepublic void onFailure(Call call, IOException e) {String message = e.getMessage();Log.d("---", "onFailure: "+message);}@Overridepublic 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,repasswordFormBody formBody = new FormBody.Builder().add("username","zhaoxuhui111111").add("password","123456").build();//TODO 2:request请求Request request = new Request.Builder().url("").post(formBody)//post请求需要设置请求体.build();//TODO 3:client发起request---》call连接Call call = client.newCall(request);//TODO 4:加入队列中(线程池)---》responsecall.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {//失败final String message = e.getMessage();handler.post(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, "失败:" + message, Toast.LENGTH_SHORT).show();}});}@Overridepublic void onResponse(Call call, Response response) throws IOException {//成功//ResponseBody 响应体ResponseBody body = response.body();final String string = body.string();//千万不要tostringhandler.post(new Runnable() {@Overridepublic 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,repasswordFormBody formBody = new FormBody.Builder().add("username","zhaoxuhui111111").add("password","123456").add("repassword","123456").build();//TODO 2:request请求Request request = new Request.Builder().url("").post(formBody)//post请求需要设置请求体.build();//TODO 3:client发起request---》call连接Call call = client.newCall(request);//TODO 4:加入队列中(线程池)---》responsecall.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {//失败final String message = e.getMessage();handler.post(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, "失败:" + message, Toast.LENGTH_SHORT).show();}});}@Overridepublic void onResponse(Call call, Response response) throws IOException {//成功//ResponseBody 响应体ResponseBody body = response.body();final String string = body.string();handler.post(new Runnable() {@Overridepublic 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(".php?stage_id=1&limit=20&page=1").get()//请求方式.build();//TODO 3:client发起request---》call连接Call call = client.newCall(request);//TODO 4:加入队列中(线程池)---》responsecall.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {//失败final String message = e.getMessage();handler.post(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, "失败:" + message, Toast.LENGTH_SHORT).show();}});}@Overridepublic void onResponse(Call call, Response response) throws IOException {//成功//ResponseBody 响应体ResponseBody body = response.body();final String string = body.string();handler.post(new Runnable() {@Overridepublic void run() {Toast.makeText(MainActivity.this, "" + string, Toast.LENGTH_SHORT).show();}});}});}
}

更多推荐

Okhttp基本操作

本文发布于:2024-03-10 08:09:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1727432.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:操作   Okhttp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!