Java OkHttp使用

本文详细介绍使用OkHttp3进行网络请求的方法,包括同步及异步GET请求、POST提交表单与字符串、Gson解析响应数据、设置超时时间、缓存管理、复用OkHttpClient实例及处理认证等。

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

本文使用eclipse编辑器,gradle依赖jar,如若未配置此环境,请转Java Eclipse配置gradle编译项目配置好环境后再查看此文

  1. 在build.gradle中添加依赖
    compile 'com.squareup.okhttp3:okhttp:3.8.1'
  2. 同步Get请求
    /**
     * 同步get请求
     */
    public static void syncGet() throws Exception{
        String urlBaidu = "http://www.baidu.com/";
        OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
        Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求
        Response response = okHttpClient.newCall(request).execute(); // 返回实体
        if (response.isSuccessful()) { // 判断是否成功
            /**获取返回的数据,可通过response.body().string()获取,默认返回的是utf-8格式;
             * string()适用于获取小数据信息,如果返回的数据超过1M,建议使用stream()获取返回的数据,
             * 因为string() 方法会将整个文档加载到内存中。*/
            System.out.println(response.body().string()); // 打印数据
        }else {
            System.out.println("失败"); // 链接失败
        }
    }
  1. 异步Get请求
    /**
     * 异步Get请求
     */
    public static void asyncGet() {
        String urlBaidu = "http://www.baidu.com/";
        OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
        Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求
        okHttpClient.newCall(request).enqueue(new Callback() { // 回调 
            
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功调用,该回调在子线程
                System.out.println(response.body().string());
            }
            
            public void onFailure(Call call, IOException e) {
                // 请求失败调用
                System.out.println(e.getMessage());
            }
        });
    }

4.Post提交表单

    /**
     * Post提交表单
     */
    public static void postFromParameters() {
        String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
        String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数
        OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
        RequestBody formBody = new FormBody.Builder().add("key", KEY).build(); // 表单键值对
        Request request = new Request.Builder().url(url).post(formBody).build(); // 请求
        okHttpClient.newCall(request).enqueue(new Callback() {// 回调

            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());//成功后的回调
            }

            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());//失败后的回调
            }
        });
    }
  1. Post提交字符串
    /**
     * Post提交字符串
     * 使用Post方法发送一串字符串,但不建议发送超过1M的文本信息
     */
    public static void postStringParameters(){
        MediaType MEDIA_TYPE = MediaType.parse("text/text; charset=utf-8");
        String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
        OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
        String string = "key=9488373060c8483a3ef6333353fdc7fe"; // 要发送的字符串
        /**
         * RequestBody.create(MEDIA_TYPE, string)
         * 第二个参数可以分别为:byte[],byteString,File,String。
         */
        Request request = new Request.Builder().url(url)
                    .post(RequestBody.create(MEDIA_TYPE,string)).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
            
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
        }); 
    }
  1. Gson解析Response的Gson对象
    /**
     * Gson解析Response的Gson对象
     */
    public static void gsonResponsePost() {
        String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
        String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数
        OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
        RequestBody formBody = new FormBody.Builder().add("key", KEY).build(); // 表单键值对
        Request request = new Request.Builder().url(url).post(formBody).build(); // 请求
        okHttpClient.newCall(request).enqueue(new Callback() {// 回调

            public void onResponse(Call call, Response response) throws IOException {
                //成功后的回调
                Gson gson = new Gson();
                Info info = gson.fromJson(response.body().string(), Info.class);
                System.out.println(info.toString());
            }

            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());//失败后的回调
            }
        });
    }
    /**
     * Java Bean
     */
    public class Info{
        int error_code; //状态码
        String reason; // 返回状态文字
        Result result; // 页面URL
        @Override
        public String toString() {
            return "Info [error_code=" + error_code + ", reason=" + reason + ", result=" + result.toString() + "]";
        }
    }
    /**
     * Java Bean
     */
    public class Result{
        String h5url;
        String h5weixin;
        @Override
        public String toString() {
            return "Result [h5url=" + h5url + ", h5weixin=" + h5weixin + "]";
        }   
    }
  1. okhttp3 设置超时时间
    /**
     * 设置超时
     * @throws IOException 
     */
    public static void timeOutPost() throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                                    .connectTimeout(10, TimeUnit.SECONDS)//设置链接超时
                                    .writeTimeout(10, TimeUnit.SECONDS) // 设置写数据超时
                                    .readTimeout(30, TimeUnit.SECONDS) // 设置读数据超时
                                    .build();
        Request request = new Request.Builder().url("http://www.baidu.com/").build();

        Response response = client.newCall(request).execute();
        System.out.println("Response completed: " + response);
    }
  1. 缓存设置
    /**
     * 缓存设置
     * @throws Exception
     */
    public static void cachePost() throws Exception {
        File sdcache = new File("D:/file");
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        OkHttpClient client = new OkHttpClient()
                .Builder()
                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))
                .build();
        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .build();

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

        String response1Body = response1.body().string();
        System.out.println("Response 1 response:          " + response1);
        System.out.println("Response 1 cache response:    " + response1.cacheResponse());
        System.out.println("Response 1 network response:  " + response1.networkResponse());

        request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
        Response response2 = client.newCall(request).execute();
        if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);

        String response2Body = response2.body().string();
        System.out.println("Response 2 response:          " + response2);
        System.out.println("Response 2 cache response:    " + response2.cacheResponse());
        System.out.println("Response 2 network response:  " + response2.networkResponse());

        System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));
    }

打印结果:

Response 1 response:          Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
Response 1 cache response:    Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
Response 1 network response:  null
Response 2 response:          Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
Response 2 cache response:    null
Response 2 network response:  Response{protocol=http/1.1, code=200, message=OK, url=https://publicobject.com/helloworld.txt}
Response 2 equals Response 1? true
  1. 复用OkHttpClient
    /**
     * 所有HTTP请求的代理设置,超时,缓存设置等都需要在OkHttpClient中设置。 如果需要更改一个请求的配置,可以使用
     * OkHttpClient.newBuilder()获取一个builder对象,
     * 该builder对象与原来OkHttpClient共享相同的连接池,配置等。
     */
    public static void shareClient() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://www.baidu.com/").build();

        try {
            // Copy to customize OkHttp for this request.
            OkHttpClient copy = client.newBuilder().readTimeout(500, TimeUnit.MILLISECONDS).build();
            Response response = copy.newCall(request).execute();
            System.out.println("Response 1 succeeded: " + response);
        } catch (IOException e) {
            System.out.println("Response 1 failed: " + e);
        }

        try {
            // Copy to customize OkHttp for this request.
            OkHttpClient copy = client.newBuilder().readTimeout(3000, TimeUnit.MILLISECONDS).build();
            Response response = copy.newCall(request).execute();
            System.out.println("Response 2 succeeded: " + response);
        } catch (IOException e) {
            System.out.println("Response 2 failed: " + e);
        }
    }
  1. OkHttp3处理验证
    /**
     * 登录验证
     * @throws IOException
     */
    public static void authenticatorPost() throws IOException {
        OkHttpClient okHttpClient = 
                new OkHttpClient
                .Builder()
                .authenticator(new Authenticator() {
                    
                    public Request authenticate(Route route, Response response) throws IOException { 
                        System.out.println(response.challenges().toString());
                        String credential = Credentials.basic("jesse", "password1");
                        return response
                                .request()
                                .newBuilder()
                                .addHeader("Authorization", credential)
                                .build();
                    }
                })
                .build();
        Request request = new Request.Builder().url("http://publicobject.com/secrets/hellosecret.txt").build();
        Response response = okHttpClient.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        System.out.println(response.body().string());
    }
Java中的OkHttp是一个高效、功能丰富的HTTP客户端库,它提供了许多高级特性,使得网络请求变得更加简单易用。下面是使用OkHttp的基本步骤: ### 1. 添加依赖 首先,需要将OkHttp添加到项目的依赖管理中。如果你正在使用Maven项目,可以在`pom.xml`文件中添加下面的依赖: ```xml <dependencies> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>最新版本号</version> </dependency> </dependencies> ``` 记得替换`最新版本号`为您实际使用OkHttp版本。 ### 2. 创建Client实例 接下来,创建一个新的`Client`实例用于发起网络请求: ```java import okhttp3.OkHttpClient; public class OkHttpClientExample { private static final OkHttpClient client = new OkHttpClient(); } ``` ### 3. 发起GET请求 使用`client.newCall()`构造一个新的`Call`实例,并通过该实例发送GET请求: ```java import okhttp3.Request; import okhttp3.Response; public void getExample() { Request request = new Request.Builder() .url("https://api.example.com/data") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println(e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); String bodyText = response.body().string(); // 处理响应体内容 System.out.println(bodyText); } }); } ``` ### 4. 发起POST请求 如果需要发起POST请求,可以使用`RequestBody`封装数据,并构建相应的`Request`: ```java String jsonPayload = "{\"key\":\"value\"}"; RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonPayload); Request request = new Request.Builder() .url("https://api.example.com/data") .post(requestBody) .build(); client.newCall(request).enqueue(new Callback()); ``` ### 相关问题: 1. **为什么选择OkHttp而不是其他库**? - OkHttp提供了高性能、简洁易用的API以及强大的错误处理机制,适用于各种规模的应用程序。 2. **OkHttp如何处理并发请求**? - OkHttp支持异步请求并提供线程池处理并发请求,同时可以控制最大并发连接数等。 3. **如何自定义OkHttp配置**? - 可以通过`NetworkInterceptors`和`ConnectionPool`等选项来自定义客户端的行为,如超时设置、日志记录、缓存策略等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值