美文网首页
Okhttp3 使用(五)

Okhttp3 使用(五)

作者: 徘徊0_ | 来源:发表于2020-05-08 10:16 被阅读0次

    Post

    在进行post请求的时候,通常RequestBody的数据都要指定Content-Type,常见的有:
    所有的MediaTypes

    MediaType 备注
    application/json JSON数据格式
    multipart/form-data 需要在表单中进行文件上传时,就需要使用该格式
    application/x-www-form-urlencoded <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
    image/png png图片格式
    text/html HTML格式
    text/plain 纯文本格式
    text/x-markdown 文本MarkDown
    text/xml XML格式
    image/gif gif图片格式
    image/jpeg jpg图片格式
    application/xhtml+xml XHTML格式
    application/xml XML数据格式
    application/pdf pdf格式
    application/msword Word文档格式
    application/octet-stream 二进制流数据(如常见的文件下载)

    Content-Type也可以使用这种方式

        public static final String FORM_DATA = "multipart/form-data;";
        public static final String IMAGE_DATA = "image/*; charset=utf-8";
        public static final String JSON_DATA = "application/json; charset=utf-8";
        public static final String VIDEO_DATA = "video/*";
        public static final String AUDIO_DATA = "audio/*";
        public static final String TEXT_DATA = "text/plain";
        public static final String APK_DATA = "application/vnd.android.package-archive";
        public static final String JAVA_DATA = "java/*";
        public static final String MESSAGE_DATA = "message/rfc822";
    
    一、post 请求(FormBody 表单)

    使用FormBody创建 RequestBody 直接使用 key - value ,传入参数

            //1,创建client
            OkHttpClient client = new OkHttpClient();
            //FormBody  创建表单请求体
            FormBody formBody = new FormBody.Builder()
                    .add("name", "zhangsan")//传入参数
                    .add("age", "11")
                    .build();
            //3,创建request
            Request request = new Request.Builder()
                    .url("--url--")//伪 url
                    .post(formBody)//请求体
                    .build();
            //异步请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //失败回调,子线程
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //成功回调,子线程
                }
            });
    
    二、 post 请求 (json)

    数据为json的时候,需要指定MediaType.parse("application/json; charset=utf-8");为json

            OkHttpClient client = new OkHttpClient();
            
            MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
            String jsonString = "{ \"name\": \"zhangsan\",\"age\": \"10\"}";//传递的json数据
            //构建requestBody
            RequestBody requestBody = RequestBody.create(JSON_TYPE, jsonString);
            
            //3,创建request
            Request request = new Request.Builder()
                    .url("--url--")
                    .post(requestBody)//请求体
                    .build();
    
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //失败回调,子线程
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //成功回调,子线程
                }
            });
    
    三、 post 请求 (file + key-value)
           OkHttpClient client = new OkHttpClient();
            
            //构建MultipartBody 
            MultipartBody multipartBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);
                    .addFormDataPart("name", "zhangsan")//传递 key - value
                    .addFormDataPart("age", "10")
                    .addFormDataPart("image", "imageName", RequestBody.create(MediaType.parse("image/png"), new File("image.png")))//上传 .png 文件
                    .build();
    
            //3,创建request
            Request request = new Request.Builder()
                    .url("--url--")
                    .post(multipartBody)//请求体
                    .build();
    
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //失败回调,子线程
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //成功回调,子线程
                }
            });
    
    
    四、自定义拦截器

    可以通过自定义拦截器,对请求作出你想要出处理,例如下面的,如果接口返回的不是成功(code!=200),则替换url

    /**
     * create by cuishuxiang
     *
     * @date : 2019/1/15
     * @description:  自定义了拦截器,当code!=200的时候,替换URL
     */
    public class ReplaceUrlInterceptor implements Interceptor {
        private static final String TAG = "ReplaceUrlInterceptor";
    
        String newUrl = "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/6/1";
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
    
            Response response = chain.proceed(request);
    
            String url = request.url().toString();//
    
            //如果接口code !=200,替换url
            while (response.code() != 200) {
                url = newUrl;
                Request newRequest = request.newBuilder().url(url).build();//这里重新构建request
                response = chain.proceed(newRequest);//生成response
            }
            return response;
        }
    }
    
    

    使用,在OkHttpClient 中添加自定义的拦截器

    OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(new ReplaceUrlInterceptor())//添加自定义的拦截器
                    .build();
    

    Http基础

    相关文章

      网友评论

          本文标题:Okhttp3 使用(五)

          本文链接:https://www.haomeiwen.com/subject/fulwrqtx.html