Java OkHttp获取请求示例

x33g5p2x  于2022-10-16 转载在 Java  
字(5.3k)|赞(0)|评价(0)|浏览(901)

在本文中,我们将用Java创建一个OkHttpGET HTTP请求示例。

OkHTTP是一个开源项目,旨在成为Android和Java应用程序的高效HTTP客户端。

OkHttp支持Android 5.0+(API级别21+)和Java 1.8+。在本文中,我们将使用Java1.8+编写代码。

Maven依赖项

首先将库作为依赖项添加到pom.xml中:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.0</version>
</dependency>

要查看此库的最新依赖项,请查看page on Maven Central

1.OkHttp GET请求Java示例

在本例中,我们将为spring boot CRUD示例项目发出GET HTTP客户端请求。这个spring-boot-crud示例项目已经部署、启动并运行。

package com.javaguides.okhttp.tutorial.crud;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpGet {

    OkHttpClient client = new OkHttpClient();

    public String run(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static void main(String[] args) throws IOException {
        OkHttpGet example = new OkHttpGet();
        String response = example.run("http://localhost:8080/api/v1/employees/1");
        System.out.println(response);
    }
}

下图显示了源代码的屏幕截图以及输出:

2.使用OkHttp同步GET

要发送同步GET请求,我们需要基于URL构建request对象并进行调用。执行后,我们返回响应的示例:

package com.javaguides.okhttp.tutorial;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpGetExample {

    OkHttpClient client = new OkHttpClient();

    public String run(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static void main(String[] args) throws IOException {
        OkHttpGetExample example = new OkHttpGetExample();
        String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
        System.out.println(response);
    }
}

输出:

OkHttp
======

An HTTP & HTTP/2 client for Android and Java applications. For more information see [the
website][website] and [the wiki][wiki].

.....

3.使用OkHttp的异步GET

现在,要进行异步GET,我们需要对调用进行排队。回调允许我们在响应可读时读取响应。这发生在响应头准备好之后。
读取响应正文可能仍会阻塞OkHttp目前不提供任何异步API来接收部分响应正文:

package com.javaguides.okhttp.tutorial;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpAsynchronousGetRequest {

    OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        OkHttpAsynchronousGetRequest example = new OkHttpAsynchronousGetRequest();
        example.run("https://raw.github.com/square/okhttp/master/README.md");
    }

    public void run(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("on Success");
                System.out.println(response.toString());
            }

            public void onFailure(Call call, IOException e) {
                System.out.println("onFailure");
            }
        });
    }
}

输出:

on Success
Response{protocol=http/1.1, code=200, message=OK, url=https://raw.githubusercontent.com/square/okhttp/master/README.md}

4.带查询参数的GET请求

最后,为了向GET请求添加查询参数,我们可以利用HttpUrl.Builder。
构建URL后,我们可以将其传递给Request对象:

package com.javaguides.okhttp.tutorial;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpGetQueryParametersExample {
    // avoid creating several instances, should be singleon
    OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws IOException {

        OkHttpGetQueryParametersExample example = new OkHttpGetQueryParametersExample();
        HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.github.com").newBuilder();
        urlBuilder.addQueryParameter("v", "3.0");
        urlBuilder.addQueryParameter("user", "RameshMF");
        String url = urlBuilder.build().toString();
        System.out.println("Print URL : " + url);
        System.out.println(example.run(url));
    }

    // Common method to execute and return response
    public String run(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}

输出:

Print URL : https://api.github.com/?v=3.0&user=RameshMF
{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":
....

5.访问Http请求头

package com.javaguides.okhttp.tutorial;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpHeadersExample {

    private final OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws Exception {
        OkHttpHeadersExample example = new OkHttpHeadersExample();
        example.run();
    }

    public void run() throws Exception {
        Request request = new Request.Builder().url("https://api.github.com/repos/square/okhttp/issues")
            .header("User-Agent", "OkHttp Headers.java").addHeader("Accept", "application/json; q=0.5")
            .addHeader("Accept", "application/vnd.github.v3+json").build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful())
                throw new IOException("Unexpected code " + response);

            System.out.println("Server: " + response.header("Server"));
            System.out.println("Date: " + response.header("Date"));
            System.out.println("Vary: " + response.headers("Vary"));
        }
    }
}

输出:

Server: GitHub.com
Date: Mon, 27 May 2019 06:59:49 GMT
Vary: [Accept]

相关文章