美文网首页Android开发Android技术知识Android开发
实例讲解OkHttp用法(get,post,form,json,

实例讲解OkHttp用法(get,post,form,json,

作者: 手指乐 | 来源:发表于2019-08-21 10:22 被阅读13次
    • 初始化

    OkHttpClient client;
    client = new OkHttpClient();
    
    • 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();
                    }
                });
    
            }
        });
    
    }
    
    • 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);
            }
        });
    
    }
    
    • post+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);
            }
        });
    
    }
    
    • 下载:

    protected void okHttpDownLoad() {
    
        String url = "https://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", "文件下载成功");
            }
        });
    }
    
    • 上传单文件:

    上传服务器为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);
            }
        });
    }
    
    • 多文件(或多种数据类型)同时上传:

    多文件(或多种数据类型)上传需要指定HTTP请求协议头的Content-Type字段为multipart/form-data
    setType(MultipartBody.FORM)让okhttp知道是多文件上传
    addFormDataPart指定需要上传的各个部分
    下例中上传了两个内容,第一个内容命名为‘title’,内容为纯文本‘wangshu’
    第二个内容命名为‘upload_file0’,内容为图片,图片名为"wangshu.jpg",图片路径为"/sdcard/wangshu.jpg"

    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());
            }
        });
    }
    
    • 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();
    
    }
    
    • 同步执行:

    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();
    

    相关文章

      网友评论

        本文标题:实例讲解OkHttp用法(get,post,form,json,

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