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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • JAVA虚拟机(JVM)以及跨平台原理(JDK、JRE、JVM)

    JAVA虚拟机(JVM)以及跨平台原理(JDK、JRE、JVM)

    2021年9月5日
    47
  • 从零开始的大数据技术学习路线指南:带你轻松成为大数据开发工程师![通俗易懂]

    从零开始的大数据技术学习路线指南:带你轻松成为大数据开发工程师![通俗易懂]之前有不少小伙伴留言和私信我关于大数据学习路线,以及咨询我一些关于有工作经验想转行大数据的问题,只言片语也讲不清。我花了一个月整理了一份我当初学习的大数据学习路线,从最基础的大数据集群搭建开始,希望能帮助到大家。

    2022年5月23日
    39
  • 苹果 find my 原理_find区别

    苹果 find my 原理_find区别什么是查我网络?2021年4月21日的苹果发布会发布了一款新的产品:AirTag,防丢器。使用的是BLE+UWB的技术。BLE通过FindMy网络解决了GPS定位的问题;而UWB解决了室内的、厘米级的精准定位问题。二者相互补充,实现了比较精准的定位,为用户提供优秀的物品防丢体验。查我网络(FindMyNetwork)是苹果公司发布的一项应用技术。这项技术比较神奇的一点是,支持这项技术的苹果设备(iPhone,iPad,AirPods,AirTag等),即使本身没有GPS

    2022年10月22日
    0
  • 十进制转换为二,八,十六进制_vb进制转换

    十进制转换为二,八,十六进制_vb进制转换进制转换原理进制转换是人们利用符号来计数的方法。进制转换由一组数码符号和两个基本因素“基数”与“位权”构成。基数是指,进位计数制中所采用的数码(数制中用来表示“量”的符号)的个数。位权是指,进位制中每一固定位置对应的单位值。在知乎有个问题下的解答很不错,可以参考:打开链接他们之间的关系如下:接下来我们一一阐述。一:(二,八,十六进制)转十进…

    2022年10月11日
    0
  • pycharm 远程调试图文_Pycharm配置远程调试的图文步骤「建议收藏」

    pycharm 远程调试图文_Pycharm配置远程调试的图文步骤「建议收藏」Pycharm配置远程调试方法总结动机一些bug由于本地环境和线上环境的不一致可能导致本地无法复现本地依赖和线上依赖版本不一致也可以导致一些问题有时一些bug跟数据相关,本地数据无法和线上数据一致有些三方平台会验证服务器的合法性或者异步回调结果,如微信支付,这时候本地无法测试如上所诉,要是有一个很方便调试远程服务器的方法,岂不美哉。通过PyCharm我们可以很方便地实现远程调试,下面详细介绍下Py…

    2022年8月28日
    1
  • 前端开发中常用的几种设计模式有哪些_设计模式原理

    前端开发中常用的几种设计模式有哪些_设计模式原理设计模式是对软件设计开发过程中反复出现的某类问题的通用解决方案。设计模式更多的是指导思想和方法论,而不是现成的代码,当然每种设计模式都有每种语言中的具体实现方式。学习设计模式更多的是理解各种模式的内在思想和解决的问题,毕竟这是前人无数经验总结成的最佳实践,而代码实现则是对加深理解的辅助。设计模式可以分为三大类:结构型模式(StructuralPatterns):通过识别系统中组件间的简单关系来简化系统的设计。 创建型模式(CreationalPatterns):处理对象的创..

    2025年7月28日
    1

发表回复

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

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