Java OkHttp使用

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

本文使用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基本使用
Java:OkHttp基本使用
500 0
|
JSON Java Apache
如果你想在Java代码中写一个Http客户端,你会选择哪一种方式?Okhttp vs Apache vs Jdk
如果你想在Java代码中写一个Http客户端,你会选择哪一种方式?Okhttp vs Apache vs Jdk
java-工具-okhttp(2)
 http://blog.csdn.net/oncealong/article/details/52096477
827 0
解决okhttp报java.lang.IllegalStateException: closed,java.lang.IllegalStateException: closed
解决okhttp报java.lang.IllegalStateException: closed,java.lang.IllegalStateException: closed
796 0
|
21天前
|
Java 开发者
Java多线程编程中的常见误区与最佳实践####
本文深入剖析了Java多线程编程中开发者常遇到的几个典型误区,如对`start()`与`run()`方法的混淆使用、忽视线程安全问题、错误处理未同步的共享变量等,并针对这些问题提出了具体的解决方案和最佳实践。通过实例代码对比,直观展示了正确与错误的实现方式,旨在帮助读者构建更加健壮、高效的多线程应用程序。 ####
|
12天前
|
缓存 Java 开发者
Java多线程编程的陷阱与最佳实践####
本文深入探讨了Java多线程编程中常见的陷阱,如竞态条件、死锁和内存一致性错误,并提供了实用的避免策略。通过分析典型错误案例,本文旨在帮助开发者更好地理解和掌握多线程环境下的编程技巧,从而提升并发程序的稳定性和性能。 ####
|
6天前
|
监控 Java 开发者
深入理解Java中的线程池实现原理及其性能优化####
本文旨在揭示Java中线程池的核心工作机制,通过剖析其背后的设计思想与实现细节,为读者提供一份详尽的线程池性能优化指南。不同于传统的技术教程,本文将采用一种互动式探索的方式,带领大家从理论到实践,逐步揭开线程池高效管理线程资源的奥秘。无论你是Java并发编程的初学者,还是寻求性能调优技巧的资深开发者,都能在本文中找到有价值的内容。 ####
|
11天前
|
安全 Java 开发者
Java中的多线程编程:从基础到实践
本文深入探讨了Java多线程编程的核心概念和实践技巧,旨在帮助读者理解多线程的工作原理,掌握线程的创建、管理和同步机制。通过具体示例和最佳实践,本文展示了如何在Java应用中有效地利用多线程技术,提高程序性能和响应速度。
42 1
|
20天前
|
安全 Java 开发者
Java 多线程并发控制:深入理解与实战应用
《Java多线程并发控制:深入理解与实战应用》一书详细解析了Java多线程编程的核心概念、并发控制技术及其实战技巧,适合Java开发者深入学习和实践参考。
40 6
|
20天前
|
Java 开发者
Java多线程编程的艺术与实践####
本文深入探讨了Java多线程编程的核心概念、应用场景及实践技巧。不同于传统的技术文档,本文以实战为导向,通过生动的实例和详尽的代码解析,引领读者领略多线程编程的魅力,掌握其在提升应用性能、优化资源利用方面的关键作用。无论你是Java初学者还是有一定经验的开发者,本文都将为你打开多线程编程的新视角。 ####