OKHttp通信使用(一)

本文介绍了OKHttp作为成熟HTTP通信机制在Android中的应用,它取代了HttpClient和HttpURLConnection。内容包括OKHttp的概念、同步与异步请求方式,以及GET和POST请求的实例,如下载文件、获取JSON数据、发送String数据、键值对和数据流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概念:

Android 提供了两种HTTP通信方式:一种是Java原生的Apache的HTTP通信:HttpClient ,另一种是android所使用的HttpURLConnection。

作为较为成熟的HTTP通信机制OKHTTP正在取代上述两种HTTP通信方式,在android 4.4版本后,Volley也剔除了HttpURLConnection,改为使用OKHTTP进行通信。它的优势在于更稳定,可以设置多个IP地址进行失败连接问题的处理等等。在进行HTTPS访问时也更加稳定和安全。

下面是OKHTTP的简单应用。主要来自于GitHub:https://github.com/square/okhttp/wiki


OKHTTP支持所有的HTTP请求方式:GET,POST,HEAD.....这里主要是进行GET与POST为例进行介绍。

OKHTTP有两种请求方式:

同步方式:

execute

异步方式:

enqueue

使用方式:

为一下所有函数定义全局变量:

private final OkHttpClient client = new OkHttpClient();

GET请求:

使用get请求下载文件,返回的是String。

 public void run() throws Exception {
        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .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 {
                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请求JSON数据:

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

    static class GistFile {
        String content;
    }

    private final Gson gson = new Gson();

    public void run_JSON() 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) {

            }

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

                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("11111111111111111111 "+entry.getKey());
                    System.out.println(entry.getValue().content);
                }
            }
        });

    }

POST请求:

使用POST发送一个String型数据:

 public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8"); //content-type
    /**
     * 发送一个string型数据
     * @throws Exception
     */
    public void run_string() throws Exception {
        String postBody = ""
                + "Releases\n"
                + "--------\n"
                + "\n"
                + " * _1.0_ May 6, 2013\n"
                + " * _1.1_ June 15, 2013\n"
                + " * _1.2_ August 11, 2013\n";

        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
                .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 {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

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

            }
        });

    }

使用POST请求发送一个键值对:

    /**
     * 发送一个post键值对参数
     * @throws Exception
     */
    public void run_keyValue() throws Exception {
        RequestBody formBody = new FormBody.Builder()
                .add("search", "Jurassic Park")
                .build();
        Request request = new Request.Builder()
                .url("https://en.wikipedia.org/w/index.php")
                .post(formBody)
                .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 {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

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

    }


使用POST发送一个数据流:

 /**
     * //发送一个流
     * @throws Exception
     */
    public void run_Streaming() throws Exception {
        RequestBody requestBody = new RequestBody() {

            @Override public MediaType contentType() {
                return MEDIA_TYPE_MARKDOWN;
            }

            @Override public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8("Numbers\n");
                sink.writeUtf8("-------\n");
                for (int i = 2; i <= 997; i++) {
                    sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
                }
            }

            private String factor(int n) {
                for (int i = 2; i < n; i++) {
                    int x = n / i;
                    if (x * i == n) return factor(x) + " × " + i;
                }
                return Integer.toString(n);
            }
        };

        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .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 {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                System.out.println(response.body().string());
            }
        });


    }










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值