关闭

okhttp用法

308人阅读 评论(0) 收藏 举报

1.get:

注意回调不是在主线程执行的,所有操作ui要runonuithread

protected void okHttpGet() {
    Request.Builder builder = new Request.
            Builder()
            .url("http://apis.juhe.cn/cook/query?key=4ecde5ed955fadaf85d96529cd98beb4&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF");
    builder.method("GET", null);
    Request request = builder.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 {
            String str = response.body().string();
            Log.d("qf", str);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "ok", Toast.LENGTH_SHORT).show();
                }
            });


        }
    });

}

2.post


protected void okHttpPost() {

    Request.Builder builder = new Request
            .Builder()
            .url("http://apis.juhe.cn/cook/query");
    RequestBody body = new FormBody
            .Builder()
            .add("key", "4ecde5ed955fadaf85d96529cd98beb4")
            .add("menu", "西红柿")
            .build();


    builder.post(body);

    Request request = builder.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 {
            String str = response.body().string();
            Log.i("zy", str);
        }
    });


}

3.json请求:

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

protected void okHttpPostJson() {

    String url = "http://192.168.1.103/test/rest/rest.php/items";
    String data = "{\"name\":\"Brett3\",\"link\":\"haha2\"}";

    Request.Builder builder = new Request.Builder().url(url);
    RequestBody body = RequestBody.create(JSON, data);
    //builder.post(body);
    builder.method("POST", body);
    Request request = builder.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 {
            String str = response.body().string();
            Log.i("zy", str);
        }
    });

}

4.下载:

protected void okHttpDownLoad() {

    String url = "http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";
    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) {
            InputStream inputStream = response.body().byteStream();
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(new File("/sdcard/wangshu.jpg"));
                byte[] buffer = new byte[2048];
                int len = 0;
                while ((len = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                }
                fileOutputStream.flush();
            } catch (IOException e) {
                Log.i("wangshu", "IOException");
                e.printStackTrace();
            }

            Log.d("wangshu", "文件下载成功");
        }
    });
}

5.上传单文件:

上传服务器为github,生成markdown文件,上传一个文件,github这个服务可以对文件中内容按照一定语法进行处理

public static final MediaType MEDIA_TYPE_MARKDOWN
        = MediaType.parse("text/x-markdown; charset=utf-8");

protected void okHttpUpdateFile() {

    File file = new File("/sdcard/DownLoad/bb.txt");
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
            .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 {

            String str = response.body().string();
            Log.i("zy", str);
        }
    });
}

6.多文件(或多种数据类型)同时上传:

private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

private void sendMultipart() {
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("title", "wangshu")
            .addFormDataPart("upload_file0"
                    , "wangshu.jpg"
                    , RequestBody.create(MEDIA_TYPE_PNG, new File("/sdcard/wangshu.jpg")))
            .build();

    Request request = new Request.Builder()
            .url("http://192.168.1.107/upload.php")
            .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 {
            Log.i("wangshu", response.body().string());
        }
    });
}

7.okhttpclient的初始化设置:

protected void initOkHttpClient() {
    //client = new OkHttpClient();

    File sdcache = getExternalCacheDir();
    int cacheSize = 10 * 1024 * 1024;
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(5, TimeUnit.SECONDS);
    builder.cache(new Cache(sdcache, cacheSize));
    client = builder.build();

}

8.同步执行:

protected void syncExcute(){
    Request.Builder builder = new Request.
            Builder()
            .url("http://apis.juhe.cn/cook/query?key=4ecde5ed955fadaf85d96529cd98beb4&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF");
    builder.method("GET", null);
    Request request = builder.build();

    try {
        Response response = client.newCall(request).execute();
        String str = response.body().string();
        Log.d("qf",str);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

new Thread(){
    @Override
    public void run() {
        syncExcute();
    }
}.start();





0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:851156次
    • 积分:8430
    • 等级:
    • 排名:第2505名
    • 原创:60篇
    • 转载:210篇
    • 译文:0篇
    • 评论:77条
    文章分类
    最新评论