OkHttp的简单使用


Android在6.0SDK中已经删除了HttpClient的相关API,比较好的代替方案是Java的HttpUrlConnection和最近比较火热的OkHttp。本篇博客主要介绍OkHttp的简单使用。

一、准备工作

OkHttp下载: https://github.com/square/okhttp

Okio依赖下载:https://github.com/square/okio

二、简单使用

1. Get请求

    /**
     * 同步请求
     */
    public static void getSync(){
        String  url = "http://ip.taobao.com/service/getIpInfo.php?ip=114.114.114.114";//淘宝的IP查询接口
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).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 {
                System.out.println(response.body().string()); //OKHttp中没有Android主线程,这里不能操作UI
            }
        });
    }    /**
     * 异步Get请求
     */
    public static void getAync() throws IOException {
        String  url = "http://ip.taobao.com/service/getIpInfo.php?ip=114.114.114.114";//淘宝的IP查询接口
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful())
            System.out.println(response.body().string());
    }

2.Post请求

(1)提交Json数据

   /**
     * post提交Json数据
     */
    public  static void postJson(String url,String json) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType type = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(type,json);
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()){
            //处理返回结果,如果需要字符串 response.body().string();
            //如果需要流  response.body().byteStream();
        }
    }


(2)提交表单数据

 public static void postForm(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder().add("key1","value1").add("key2","value2").add("key...","value...").build();
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()){
            //处理返回结果,如果需要字符串 response.body().string();
            //如果需要流  response.body().byteStream();
        }
    }

3.上传文件

  /**
     *
     * @param file 上传的文件
     * @param url 上传文件的url
     * @throws Exception
     */
    public static void uploadFile(File file,String url) throws Exception {
        OkHttpClient client = new OkHttpClient();

        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), fileBody)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
            System.out.println(response.body().string());
        }
    }

4.下载文件跟普通的请求差不多, 只是使用了请求为InputStream.

 /**
     *
     * @param url 下载地址
     * @param downPath 下载存放路径
     */
    public static void downloadFile(String url,String downPath) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        FileOutputStream fos = null;
        InputStream is = null;
        byte[] buffer = new byte[1024];
        String fileName = url.substring(url.lastIndexOf('/'));
        if (response.isSuccessful()){
            try {
                int lenth = 0;
                is = response.body().byteStream();
                fos = new FileOutputStream(new File(downPath,fileName));
                while ((lenth = is.read(buffer))>0){
                    fos.write(buffer,0,lenth);
                }
                fos.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if (fos != null){
                    fos.close();
                }
                if (is != null){
                    is.close();
                }
            }
        }

    }







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值