面试题网络Android

okhttp上传文件

2019-10-15  本文已影响0人  残非

文件上传地址

private String upload_url = "http://yun918.cn/study/public/file_upload.php";

工具类

public class Utils {

    //sd卡是否存在
    public static boolean sdCardIsAvailable(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        }
        return false;
    }

    //获取sd卡路径
    public static String getSDPath(){
        File sdDir = null;
        if(sdCardIsAvailable()){
            sdDir = Environment.getExternalStorageDirectory(); //获取根目录
        }
        return sdDir.toString();
    }
}

文件上传的代码

//okhttp上传文件
private void uploadOkHttp(){
    //sd卡图片文件
    File file = new File(Utils.getSDPath()+"/d.jpg");
    //上传文件的格式
    String img_format = "image/jpg";
    //封装文件格式
    RequestBody requestFormat = RequestBody.create(MediaType.parse(img_format),file);
    //文件内容
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file",file.getName(),requestFormat)
            .build();
    //Okhttp网络数据传递
    OkHttpClient client = new OkHttpClient.Builder()
            .build();
    Request request = new Request.Builder()
            .url(upload_url)
            .post(requestBody)
            .build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i("onFailure",e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.i("onResponse",response.body().string());
        }
    });
}
上一篇下一篇

猜你喜欢

热点阅读