Okhttp3 使用(五)

Post

在進行post請求的時候,通常RequestBody的數(shù)據(jù)都要指定Content-Type,常見的有:
所有的MediaTypes

MediaType 備注
application/json JSON數(shù)據(jù)格式
multipart/form-data 需要在表單中進行文件上傳時,就需要使用該格式
application/x-www-form-urlencoded <form encType=””>中默認的encType,form表單數(shù)據(jù)被編碼為key/value格式發(fā)送到服務器(表單默認的提交數(shù)據(jù)的格式)
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數(shù)據(jù)格式
application/pdf pdf格式
application/msword Word文檔格式
application/octet-stream 二進制流數(shù)據(jù)(如常見的文件下載)

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創(chuàng)建 RequestBody 直接使用 key - value ,傳入?yún)?shù)

        //1,創(chuàng)建client
        OkHttpClient client = new OkHttpClient();
        //FormBody  創(chuàng)建表單請求體
        FormBody formBody = new FormBody.Builder()
                .add("name", "zhangsan")//傳入?yún)?shù)
                .add("age", "11")
                .build();
        //3,創(chuàng)建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) {
                //失敗回調(diào),子線程
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //成功回調(diào),子線程
            }
        });
二、 post 請求 (json)

數(shù)據(jù)為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數(shù)據(jù)
        //構建requestBody
        RequestBody requestBody = RequestBody.create(JSON_TYPE, jsonString);
        
        //3,創(chuàng)建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) {
                //失敗回調(diào),子線程
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //成功回調(diào),子線程
            }
        });
三、 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,創(chuàng)建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) {
                //失敗回調(diào),子線程
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //成功回調(diào),子線程
            }
        });

四、自定義攔截器

可以通過自定義攔截器,對請求作出你想要出處理,例如下面的,如果接口返回的不是成功(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基礎

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容