OkHttp简介及示例大全

乔欣 Java经验 发布时间:2023-02-01 11:01:20 阅读数:10217 1
下文笔者讲述OkHttp组件如何发送Http请求及OkHttp请求的示例分享,如下所示

OkHttp简介

 OkHttp是一个处理网络请求的开源项目
   是安卓端最火热的轻量级框架
   由移动支付Square公司贡献(该公司还贡献了Picasso) 
   用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient,现在已经打不出来)

OkHttp实现思路:
    1.引入依赖
	2.编写代码

例:引入OkHttp依赖
pom.xml
<dependency>
	  <groupId>com.squareup.okhttp3</groupId>
	  <artifactId>okhttp</artifactId>
	  <version>4.2.2</version>
	</dependency>

同步获取请求

package com.java265.http;
import okhttp3.Headers;
import okhttp3.OKHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class OkHttpExample1 {
 
    // only one client, singleton, better puts it in a factory, 
	// multiple instances will create more memory.
    private final OkHttpClient httpClient = new OkHttpClient();
 
    public static void main(String[] args) throws IOException {
        OkHttpExample1 obj = new OkHttpExample1();
        obj.sendGETSync();
    }
 
    private void sendGETSync() throws IOException {
        Request request = new Request.Builder()
                .url("https://java265.com/get")
                .addHeader("custom-key", "java265")  // add request headers
                .addHeader("User-Agent", "OkHttp Bot")
                .build();
 
        try (Response response = httpClient.newCall(request).execute()) {
 
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 
            // Get response headers
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }
 
            // Get response body
            System.out.println(response.body().string());
        }
    } 
}

异步获取请求

package com.java265.okhttp;
 
import okhttp3.*;
import java.io.IOException;
 
public class OkHttpExample2 {
 
    // only one client
    private final OkHttpClient httpClient = new OkHttpClient();
 
    public static void main(String[] args) throws IOException {
        OkHttpExample2 obj = new OkHttpExample2();
        obj.sendGET();
    }
 
    private void sendGET() throws IOException {
 
        Request request = new Request.Builder()
                .url("https://httpbin.org/get")
                .addHeader("custom-key", "java265")  // add request headers
                .addHeader("User-Agent", "OkHttp Bot")
                .build();
 
        httpClient.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 {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 
                    // Get response headers
                    Headers responseHeaders = response.headers();
                    for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                    }
 
                    // Get response body
                    System.out.println(responseBody.string());
                }
            }
        });
 
    }
 
}

POST请求–表单参数

使用RequestBody参数添加
package com.java265.http;
 
import okhttp3.*;
 
import java.io.IOException;
 
public class OkHttpExample3 {
 
    private final OkHttpClient httpClient = new OkHttpClient();
 
    public static void main(String[] args) throws IOException {
        OkHttpExample3 obj = new OkHttpExample3();
        obj.sendPOST();
    }
 
    private void sendPOST() throws IOException {
 
        // form parameters
        RequestBody formBody = new FormBody.Builder()
                .add("username", "abc")
                .add("password", "123")
                .add("custom", "secret")
                .build();
 
        Request request = new Request.Builder()
                .url("https://httpbin.org/post")
                .addHeader("User-Agent", "OkHttp Bot")
                .post(formBody)
                .build();
 
        try (Response response = httpClient.newCall(request).execute()) {
 
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 
            // Get response body
            System.out.println(response.body().string());
        }
 
    }
 
}

POST请求-JSON

手动创建JSON RequestBody
package com.java265.http;
 
import okhttp3.*;
 
import java.io.IOException;
 
public class OkHttpExample4 {
 
    private final OkHttpClient httpClient = new OkHttpClient();
 
    public static void main(String[] args) throws IOException {
        OkHttpExample4 obj = new OkHttpExample4();
        obj.sendPOST();
    }
 
    private void sendPOST() throws IOException {
 
        // json formatted data
        String json = new StringBuilder()
                .append("{")
                .append("\"name\":\"java265\",")
                .append("\"notes\":\"hello\"")
                .append("}").toString();
 
		// json request body
        RequestBody body = RequestBody.create(
                json,
                MediaType.parse("application/json; charset=utf-8")
        );
 
        Request request = new Request.Builder()
                .url("https://httpbin.org/post")
                .addHeader("User-Agent", "OkHttp Bot")
                .post(body)
                .build();
 
        try (Response response = httpClient.newCall(request).execute()) {
 
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 
            // Get response body
            System.out.println(response.body().string());
        }
    } 
}

OkHttp认证

使用HTTP基本身份验证的简单Spring Security WebApp
使用OkHttp库对其进行测试
直接在Request标头认证

Request request = new Request.Builder()
		.url("http://localhost:8080/books")
		.addHeader("Authorization", Credentials.basic("user", "password"))
		.build();


创建一个Authenticator
更灵活地处理身份验证

private final Authenticator authenticator = new Authenticator() {
        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            if (response.request().header("Authorization") != null) {
                return null; // Give up, we've already attempted to authenticate.
            }
 
            System.out.println("Authenticating for response: " + response);
            System.out.println("Challenges: " + response.challenges());
            String credential = Credentials.basic("user", "password");
            return response.request().newBuilder()
                    .header("Authorization", credential)
                    .build();
        }
    };
 
    private final OkHttpClient httpClient = new OkHttpClient
		.Builder()
		.authenticator(authenticator)
		.build();

OkHttp禁用重定向

 
private final OkHttpClient httpClient = new OkHttpClient.Builder()
            .followRedirects(false)
            .build();

超时,5秒

private final OkHttpClient httpClient = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202302/16752205175606.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者