okHttp用法总结

发布于 2018-03-24  43 次阅读


注意:除了需要引okhttp包外还需要引okio包

维护cookie

private CookieJar cookieJar = new CookieJar() {
    private final Map<String, List<Cookie>> cookiesMap = new HashMap<String, List<Cookie>>();

    public void saveFromResponse(HttpUrl arg0, List<Cookie> arg1) {
        String host = arg0.host();
        List<Cookie> cookiesList = cookiesMap.get(host);
        if (cookiesList != null) {
            cookiesMap.remove(host);
        }
        cookiesMap.put(host, arg1);
    }

    public List<Cookie> loadForRequest(HttpUrl arg0) {
        List<Cookie> cookiesList = cookiesMap.get(arg0.host());
        return cookiesList != null ? cookiesList : new ArrayList<Cookie>();
    }
};

//创建okHttpClient时使用cookieJar
private OkHttpClient okHttpClient = new OkHttpClient.Builder().cookieJar(cookieJar).build();

同步POST

OkHttpClient client = new OkHttpClient();
FormBody.Builder formBody = new FormBody.Builder();
formBody.add("username", mEmail);
formBody.add("password", mPassword);
Request request = new Request.Builder()
        .url(basic_url + "user/login")
        .post(formBody.build())
        .build();
Response response = null;
try {
    response = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}

异步GET

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url(basic_url + "book/entireList")
        .build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.e(TAG, "onError:" + e);
        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT);
        loadComplete();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        try{
            List<BookBean> result= new Gson().fromJson(response.body().string(),new TypeToken<List<BookBean>>(){}.getType());
            mBookAdapter.addAll(result);
        }catch (Exception e){

        }
        loadComplete();
    }
});

onResponse里为执行成功时的操作,而onFailure里为执行失败时的操作

同步GET,异步POST

根据以上两种用法,易得

上传图片

采用MultipartBody,除了可以添加文件外,也能添加参数

private void upImage() {
    OkHttpClient mOkHttpClent = new OkHttpClient();
    File file = new File(path);
    MultipartBody.Builder builder = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", file.getName(),
                    RequestBody.create(MediaType.parse("image/jpg"), file))
            .addFormDataPart("bookId",getIntent().getIntExtra("bookId",0)+"");

    RequestBody requestBody = builder.build();

    Request request = new Request.Builder()
            .url(basic_url+"file/image")
            .post(requestBody)
            .build();
    Call call = mOkHttpClent.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
          
        }
    });