首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >android-okhttp

android-okhttp

作者头像
tea9
发布2022-07-16 15:35:57
发布2022-07-16 15:35:57
5060
举报
文章被收录于专栏:tea9的博客tea9的博客

github地址 https://github.com/square/okhttp //引入okhttp包 private final OkHttpClient client = new OkHttpClient();

代码语言:javascript
复制
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) 
        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        }
      
    }
});

//异步执行 //Asynchronous Get(异步Get)

代码语言:javascript
复制
//在一个工作线程中下载文件,当响应可读时回调Callback接口。读取响应时会阻塞当前线程。OkHttp现阶段不提供异步api来接收响应体。
public void run() throws Exception {
    Request request = new Request.Builder()
            //.url("http://publicobject.com/helloworld.txt")
            .url("http://gold.xitu.io/")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            Headers responseHeaders = response.headers();
            for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }

            System.out.println(response.body().string());
        }
    });
}

//////////////////////////// //开线程同步get请求

代码语言:javascript
复制
private void getRequest() {
    final Request request = new Request.Builder()
            .get()
            .tag(this)
            .url("http://gold.xitu.io")
            .build();
    new Thread(new Runnable() {
        @Override
        public void run() {
            Response response = null;
            try {
                response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    System.out.println("zzz" + response.body().string());
                    Log.i("xx", "打印GET响应的数据:" + response.body().string());
                } else {
                    throw new IOException("Unexpected code " + response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

//////////////////////////////////////// /////////////////////////////// //异步get解析json 使用gson private final OkHttpClient client = new OkHttpClient(); private final Gson gson = new Gson();

代码语言:javascript
复制
public void run5() throws Exception {
    Request request = new Request.Builder()
            .url("https://api.github.com/gists/c2a7c39532239ff261be")
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

//                Headers responseHeaders = response.headers();
//                for (int i = 0, size = responseHeaders.size(); i < size; i++) {
//                    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
//                }
//
            // System.out.println("aaa"+response.body().string());
            Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
            for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
                System.out.println("key" + entry.getKey());
                System.out.println("content" + entry.getValue().content);
                System.out.println("type" + entry.getValue().type);
            }
        }
    });

//        Response response = client.newCall(request).execute();
//        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//
//        Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
//        for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
//            System.out.println(entry.getKey());
//            System.out.println(entry.getValue().content);
//        }
}

static class Gist {
    Map<String, GistFile> files;
}

static class GistFile {
    String content;
    String type;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档