websocket token认证(websocket协议格式)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mazaiting/article/details/78129542 JavaOkHttp使用本文使用eclipse编辑器,gradle依赖j…

大家好,又见面了,我是你们的朋友全栈君。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mazaiting/article/details/78129542

Java OkHttp使用

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

  1. 在build.gradle中添加依赖
    compile 'com.squareup.okhttp3:okhttp:3.8.1'
  2. 同步Get请求

     
     
     
  1. /**
  2. * 同步get请求
  3. */
  4. public static void syncGet() throws Exception{
  5. String urlBaidu = "http://www.baidu.com/";
  6. OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
  7. Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求
  8. Response response = okHttpClient.newCall(request).execute(); // 返回实体
  9. if (response.isSuccessful()) { // 判断是否成功
  10. /**获取返回的数据,可通过response.body().string()获取,默认返回的是utf-8格式;
  11. * string()适用于获取小数据信息,如果返回的数据超过1M,建议使用stream()获取返回的数据,
  12. * 因为string() 方法会将整个文档加载到内存中。*/
  13. System. out.println(response.body(). string()); // 打印数据
  14. } else {
  15. System. out.println( "失败"); // 链接失败
  16. }
  17. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  1. 异步Get请求

     
     
     
  1. /**
  2. * 异步Get请求
  3. */
  4. public static void asyncGet() {
  5. String urlBaidu = "http://www.baidu.com/";
  6. OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
  7. Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求
  8. okHttpClient.newCall(request).enqueue( new Callback() { // 回调
  9. public void onResponse(Call call, Response response) throws IOException {
  10. // 请求成功调用,该回调在子线程
  11. System. out.println(response.body(). string());
  12. }
  13. public void onFailure(Call call, IOException e) {
  14. // 请求失败调用
  15. System. out.println(e.getMessage());
  16. }
  17. });
  18. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

4.Post提交表单


     
     
     
  1. /**
  2. * Post提交表单
  3. */
  4. public static void postFromParameters() {
  5. String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
  6. String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数
  7. OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
  8. RequestBody formBody = new FormBody.Builder(). add( "key", KEY).build(); // 表单键值对
  9. Request request = new Request.Builder().url(url).post(formBody).build(); // 请求
  10. okHttpClient.newCall(request).enqueue( new Callback() { // 回调
  11. public void onResponse(Call call, Response response) throws IOException {
  12. System. out.println(response.body(). string()); //成功后的回调
  13. }
  14. public void onFailure(Call call, IOException e) {
  15. System. out.println(e.getMessage()); //失败后的回调
  16. }
  17. });
  18. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  1. Post提交字符串

     
     
     
  1. /**
  2. * Post提交字符串
  3. * 使用Post方法发送一串字符串,但不建议发送超过1M的文本信息
  4. */
  5. public static void postStringParameters(){
  6. MediaType MEDIA_TYPE = MediaType.parse( "text/text; charset=utf-8");
  7. String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
  8. OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
  9. String string = "key=9488373060c8483a3ef6333353fdc7fe"; // 要发送的字符串
  10. /**
  11. * RequestBody.create(MEDIA_TYPE, string)
  12. * 第二个参数可以分别为:byte[],byteString,File,String。
  13. */
  14. Request request = new Request.Builder().url(url)
  15. .post(RequestBody.create(MEDIA_TYPE, string)).build();
  16. okHttpClient.newCall(request).enqueue( new Callback() {
  17. public void onResponse(Call call, Response response) throws IOException {
  18. System. out.println(response.body(). string());
  19. }
  20. public void onFailure(Call call, IOException e) {
  21. System. out.println(e.getMessage());
  22. }
  23. });
  24. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  1. Gson解析Response的Gson对象

     
     
     
  1. /**
  2. * Gson解析Response的Gson对象
  3. */
  4. public static void gsonResponsePost() {
  5. String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
  6. String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数
  7. OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
  8. RequestBody formBody = new FormBody.Builder(). add( "key", KEY).build(); // 表单键值对
  9. Request request = new Request.Builder().url(url).post(formBody).build(); // 请求
  10. okHttpClient.newCall(request).enqueue( new Callback() { // 回调
  11. public void onResponse(Call call, Response response) throws IOException {
  12. //成功后的回调
  13. Gson gson = new Gson();
  14. Info info = gson.fromJson(response.body(). string(), Info.class);
  15. System. out.println(info.toString());
  16. }
  17. public void onFailure(Call call, IOException e) {
  18. System. out.println(e.getMessage()); //失败后的回调
  19. }
  20. });
  21. }
  22. /**
  23. * Java Bean
  24. */
  25. public class Info{
  26. int error_code; //状态码
  27. String reason; // 返回状态文字
  28. Result result; // 页面URL
  29. @ Override
  30. public String toString( ) {
  31. return "Info [error_code=" + error_code + ", reason=" + reason + ", result=" + result.toString() + "]";
  32. }
  33. }
  34. /**
  35. * Java Bean
  36. */
  37. public class Result{
  38. String h5url;
  39. String h5weixin;
  40. @ Override
  41. public String toString( ) {
  42. return "Result [h5url=" + h5url + ", h5weixin=" + h5weixin + "]";
  43. }
  44. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  1. okhttp3 设置超时时间

     
     
     
  1. /**
  2. * 设置超时
  3. * @throws IOException
  4. */
  5. public static void timeOutPost() throws IOException {
  6. OkHttpClient client = new OkHttpClient.Builder()
  7. .connectTimeout( 10, TimeUnit.SECONDS) //设置链接超时
  8. .writeTimeout( 10, TimeUnit.SECONDS) // 设置写数据超时
  9. .readTimeout( 30, TimeUnit.SECONDS) // 设置读数据超时
  10. .build();
  11. Request request = new Request.Builder().url( "http://www.baidu.com/").build();
  12. Response response = client.newCall(request).execute();
  13. System.out.println( "Response completed: " + response);
  14. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  1. 缓存设置

     
     
     
  1. /**
  2. * 缓存设置
  3. * @throws Exception
  4. */
  5. public static void cachePost() throws Exception {
  6. File sdcache = new File( "D:/file");
  7. int cacheSize = 10 * 1024 * 1024; // 10 MiB
  8. OkHttpClient client = new OkHttpClient()
  9. .Builder()
  10. .cache( new Cache(sdcache.getAbsoluteFile(), cacheSize))
  11. .build();
  12. Request request = new Request.Builder()
  13. .url( "http://publicobject.com/helloworld.txt")
  14. .build();
  15. Response response1 = client.newCall(request).execute();
  16. if (!response1.isSuccessful()) throw new IOException( "Unexpected code " + response1);
  17. String response1Body = response1.body(). string();
  18. System. out.println( "Response 1 response: " + response1);
  19. System. out.println( "Response 1 cache response: " + response1.cacheResponse());
  20. System. out.println( "Response 1 network response: " + response1.networkResponse());
  21. request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
  22. Response response2 = client.newCall(request).execute();
  23. if (!response2.isSuccessful()) throw new IOException( "Unexpected code " + response2);
  24. String response2Body = response2.body(). string();
  25. System. out.println( "Response 2 response: " + response2);
  26. System. out.println( "Response 2 cache response: " + response2.cacheResponse());
  27. System. out.println( "Response 2 network response: " + response2.networkResponse());
  28. System. out.println( "Response 2 equals Response 1? " + response1Body. equals(response2Body));
  29. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

打印结果:


     
     
     
  1. Response 1 response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  2. Response 1 cache response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  3. Response 1 network response: null
  4. Response 2 response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  5. Response 2 cache response: null
  6. Response 2 network response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  7. Response 2 equals Response 1? true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 复用OkHttpClient

     
     
     
  1. /**
  2. * 所有HTTP请求的代理设置,超时,缓存设置等都需要在OkHttpClient中设置。 如果需要更改一个请求的配置,可以使用
  3. * OkHttpClient.newBuilder()获取一个builder对象,
  4. * 该builder对象与原来OkHttpClient共享相同的连接池,配置等。
  5. */
  6. public static void shareClient() {
  7. OkHttpClient client = new OkHttpClient();
  8. Request request = new Request.Builder().url( "http://www.baidu.com/").build();
  9. try {
  10. // Copy to customize OkHttp for this request.
  11. OkHttpClient copy = client.newBuilder().readTimeout( 500, TimeUnit.MILLISECONDS).build();
  12. Response response = copy.newCall(request).execute();
  13. System. out.println( "Response 1 succeeded: " + response);
  14. } catch (IOException e) {
  15. System. out.println( "Response 1 failed: " + e);
  16. }
  17. try {
  18. // Copy to customize OkHttp for this request.
  19. OkHttpClient copy = client.newBuilder().readTimeout( 3000, TimeUnit.MILLISECONDS).build();
  20. Response response = copy.newCall(request).execute();
  21. System. out.println( "Response 2 succeeded: " + response);
  22. } catch (IOException e) {
  23. System. out.println( "Response 2 failed: " + e);
  24. }
  25. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  1. OkHttp3处理验证

     
     
     
  1. /**
  2. * 登录验证
  3. * @throws IOException
  4. */
  5. public static void authenticatorPost() throws IOException {
  6. OkHttpClient okHttpClient =
  7. new OkHttpClient
  8. .Builder()
  9. .authenticator( new Authenticator() {
  10. public Request authenticate(Route route, Response response) throws IOException {
  11. System.out.println( response.challenges().toString());
  12. String credential = Credentials.basic( "jesse", "password1");
  13. return response
  14. . request()
  15. .newBuilder()
  16. .addHeader( "Authorization", credential)
  17. .build();
  18. }
  19. })
  20. .build();
  21. Request request = new Request.Builder().url( "http://publicobject.com/secrets/hellosecret.txt").build();
  22. Response response = okHttpClient.newCall( request). execute();
  23. if (! response.isSuccessful()) throw new IOException( "Unexpected code " + response);
  24. System.out.println( response.body(). string());
  25. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

代码下载

    </div>
    <!--  --></div>            </div>
            </div>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/126773.html原文链接:https://javaforall.net

(0)
上一篇 2022年4月17日 下午2:40
下一篇 2022年4月17日 下午2:40


相关推荐

  • 嵌入式Linux开发简介

    嵌入式Linux开发简介目录一 嵌入式 Linux 开发有那些内容二 日常工作中的开发流程是怎样的 三 搭建开发环境需要做那些事情 一 嵌入式 Linux 开发有那些内容 嵌入式 除了电脑之外 其他可以运行程序的设备都是嵌入式设备 所谓嵌入就是将 CPU 嵌入一个设备 让其具有运行程序的能力 计算能力 比如智能手表 所有的单片机开发都是嵌入式设备 嵌入式 Linux 就是指嵌入式设备上运行 Linux 操作系统 类似运行 Windows 系统的电脑 嵌入式 Linux 系统 就相当于一套完整的 PC 软件系统 与 Windows 不同的是 Linux 的各

    2026年3月19日
    2
  • [苹果开发者账号]06 转让开发者账号后,开发者年费自动续费问题

    [苹果开发者账号]06 转让开发者账号后,开发者年费自动续费问题由于用户 A 又开通了自动续费 所以到了续费时间 又自动扣了用户 A688 元 但用户 B 对应的苹果开发者账号并没有续费 但用户 A 这时候都已经不是苹果开发者了 结果扣了用户 A 年费 688 元 用户 A 已经不是苹果开发者了 不存在续费开发者账号了 1 由于用户 A 从公司离职了 所以把用户 A 的苹果开发者账号转让给了用户 B 绑定了用户 B 的 AppleID 1 用户 A 是某公司的苹果开发者账号的持有人 绑定了用户 A 的 AppleID 原因账号转让的功能 没有把用户 A 订阅的开发者账号业务转让给用户 B 2 用户 B 变成为苹果开发者

    2026年3月19日
    2
  • 常用的Java注释标签

    常用的Java注释标签1 nbsp nbsp 常用 Java 注释标签 Javacommentt author nbsp 作者适用范围 文件 类 方法 多个作者使用多个 author 标签标识 javadoc 中显示按输入时间顺序罗列 例 author nbsp Leo Yao param nbsp 输入参数的名称 nbsp 说明适用范围 方法例 paramstrtheS 用来存放输出信息 r

    2026年3月17日
    2
  • 交换机与路由器的区别

    交换机与路由器的区别路由器 Router 亦称选径器 是在网络层实现互连的设备 它比网桥更加复杂 也具有更大的灵活性 路由器有更强的异种网互连能力 连接对象包括局域网和广域网 过去路由器多用于广域网 近年来 由于路由器性能有了很大提高 价格下降到与网桥接近 因此在局域网互连中也越来越多地使用路由器 路由器是一种连接多个网络或网段的网络设备 它能将不同网络或网段之间的数据信息进行 翻译 以使它们能够相互 读 懂对方的

    2026年3月19日
    2
  • activity启动FLAG之FLAG_ACTIVITY_CLEAR_TASK「建议收藏」

    activity启动FLAG之FLAG_ACTIVITY_CLEAR_TASK「建议收藏」随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)官方文档解释:IfsetinanIntentpassedtoContext.startActivity(),thisflagwillcauseanyexistingtaskthat…

    2022年7月17日
    17
  • 软件漏洞分析简述

    软件漏洞分析简述软件漏洞1.1漏洞的定义漏洞,也叫脆弱性(英语:Vulnerability),是指计算机系统安全方面的缺陷,使得系统或其应用数据的保密性、完整性、可用性、访问控制等面临威胁。漏洞在各时间阶段的名称根据是否公开分为:未公开漏洞、已公开漏洞根据漏洞是否发现分为:未知漏洞、已知漏洞根据补丁和利用价值是否发布分为:0day漏洞、1day漏洞、历史漏洞图1漏洞在各时间阶段的名称漏洞的特…

    2022年5月20日
    63

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号