当前位置: 代码迷 >> 综合 >> Android OKHTTP 请求.上传.下载
  详细解决方案

Android OKHTTP 请求.上传.下载

热度:16   发布时间:2023-11-15 19:32:53.0

导包:

compile 'com.squareup.okhttp3:okhttp:3.9.0'
权限:(联网.读.写)

 <uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

请求:get

  public void btnForGet(View view) {OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().get().url("http://apicloud.mob.com/v1/cook/category/query?key=20a62b62d01c0").build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {//当请求失败的时候,这个方法会被执行System.out.println("请求失败 : " + e.getMessage());}@Overridepublic void onResponse(Call call, Response response) throws IOException {//当请求成功,该方法会被执行String result = response.body().string();System.out.println("异步请求结果 : " + result);}});//同步请求
//        new Thread(){
//            @Override
//            public void run() {
//                try {
//                    //创建Okhttpclient对象
//                    OkHttpClient okHttpClient = new OkHttpClient();
//                    Request request = new Request.Builder()
//                            .get()//get请求
//                            .url("http://apicloud.mob.com/v1/cook/category/query?key=20a62b62d01c0")
//                            .build();
//                    //配置请求相关参数
//                    Call call = okHttpClient.newCall(request);
//                    //服务器返回的响应对象
//                    Response response = call.execute();
//
//                    String result = response.body().string();
//
//                    System.out.println("结果 : "+result);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();}


请求:post

 public void btnForPost(View view) {OkHttpClient okHttpClient = new OkHttpClient();//构建一个请求体FormBody body = new FormBody.Builder().add("mobile", "13654897654").add("password", "123456").build();//构建请求项Request request = new Request.Builder().post(body).url("http://120.27.23.105/user/login").build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {//请求失败,会被执行}@Overridepublic void onResponse(Call call, Response response) throws IOException {//请求成功的时候会被执行//得到服务器返回的请求结果String result = response.body().string();System.out.println("post异步请求 : " + result);handler.post(new Runnable() {@Overridepublic void run() {//切到主线程}});}});}


上传1:

 public void btnOnUpload(View view) {upFile();}private void upFile() {/* 第一个要上传的file */File file1 = new File("/storage/emulated/0/Pictures/Screenshots/a.png");RequestBody fileBody1 = RequestBody.create(MediaType.parse("application/octet-stream"), file1);String file1Name = "testFile1.txt";boolean exists = file1.exists();Log.d("MainActivity", "exists:" + exists);Log.d("MainActivity", "file1:" + file1);/* form的分割线,自己定义 */String boundary = "xx--------------------------------------------------------------xx";MultipartBody mBody = new MultipartBody.Builder(boundary).setType(MultipartBody.FORM)/* 上传一个普通的String参数 , key 叫 "p" */.addFormDataPart("p", "你大爷666")/* 底下是上传了两个文件 */.addFormDataPart("file", file1Name, fileBody1).build();/* 下边的就和post一样了 */OkHttpClient okHttpClient = new OkHttpClient();//http://120.27.23.105/file/uploadRequest request = new Request.Builder().url("http://120.27.23.105/file/upload").post(mBody).build();okHttpClient.newCall(request).enqueue(new Callback() {public void onResponse(Call call, Response response) throws IOException {final String bodyStr = response.body().string();final boolean ok = response.isSuccessful();runOnUiThread(new Runnable() {public void run() {if (ok) {Toast.makeText(MainActivity.this, bodyStr, Toast.LENGTH_SHORT).show();Log.d("MainActivity", "成功");} else {Log.d("MainActivity", "成功2");Toast.makeText(MainActivity.this, "server error : " + bodyStr, Toast.LENGTH_SHORT).show();}}});}public void onFailure(Call call, final IOException e) {runOnUiThread(new Runnable() {public void run() {Log.d("MainActivity", "错误");Toast.makeText(MainActivity.this, "错误" + e.toString(), Toast.LENGTH_SHORT).show();}});}});}

上传2:

  //作业上传public void btnOnUpload(View view){upLoadFile();}/*** 上传文件*/private void upLoadFile(){OkHttpClient okHttpClient = new OkHttpClient();MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)//设置类型 以表单的形式提交.addFormDataPart("uid","3577")//create  medieaType : 上传文件类型  path : 上传的文件路劲.addFormDataPart("file","img.png",RequestBody.create(MediaType.parse("img/png"),new File(Environment.getExternalStorageDirectory(),"img.png"))).build();Request request = new Request.Builder().post(body).url("http://120.27.23.105/file/upload").build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {//失败System.out.println("失败");}@Overridepublic void onResponse(Call call, Response response) throws IOException {System.out.println("上传消息 : "+response.body().string());}});}




下载:

 //下载操作public void btnDownload(View view) {OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().url("http://msoftdl.360.cn/mobile/shouji360/360safesis/198227/360MobileSafe_7.7.3.1016.apk")//下载地址.get().build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {//失败f}@Overridepublic void onResponse(Call call, Response response) throws IOException {//成功//思路:从服务器上来 -> 下载到本地(sdcard)//得到服务响应过来的IO流InputStream is = response.body().byteStream();//读取流里面的内容,写到sdcardbyte[] buffer = new byte[1024];int len = 0;File file = new File(Environment.getExternalStorageDirectory(), "Mobliesafe_360.apk");FileOutputStream fos = new FileOutputStream(file);while ((len = is.read(buffer)) != -1) {//数据已经写到了输出流fos.write(buffer, 0, len);fos.flush();}fos.close();is.close();System.out.println("下载成功");}});}


















  相关解决方案