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>

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Cloneable_c++list容器

    Cloneable_c++list容器Cloneable类开心一笑开心是最重要的…..哥要出国旅游,让三哥帮忙看家,临走前特别交代:家里的藏獒随便逗,别惹鹦鹉。之后,三哥怎么逗藏獒,藏獒都不咬人。三哥心想:藏獒都这样,这鹦鹉也就一破鸟,能把我怎样?遂逗鹦鹉玩。结果,鹦鹉开口说话:咬他!藏獒扑上……三哥,享年27……自我介绍大家好,我叫能复制,英文名字叫“Cloneable”,住java.lang这个家,我这个人怎么说,

    2022年10月14日
  • Java—重写与重载的区别

    Java—重写与重载的区别Java—重写与重载的区别这几周开始看Java的知识,发现有一个有趣的现象就是,前两天刚看过的知识点,过一天又忘掉了。而且很多东西堆在脑子里像浆糊一样。所以边学习边总结是很重要的,今天想写一篇关于重写和重载的博客,为什么?因为面试会问啊,这是基础中比较重要的地方,但我百度了几篇博客之后发现写的都差强人意,各有缺点,但是!!访问量都特别高,所以我决定自己好好总结一篇自己的博客,也算是给自己的学习…

  • webstorm2021.11.4激活码[最新免费获取]

    (webstorm2021.11.4激活码)好多小伙伴总是说激活码老是失效,太麻烦,关注/收藏全栈君太难教程,2021永久激活的方法等着你。IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.cn/100143.htmlF6EG2ZUBVX-eyJsaWNlbnNlSWQi…

  • 谷歌的营销策略分析_反谷歌法

    谷歌的营销策略分析_反谷歌法谷歌YSlow准则YSlow可以对网站的页面进行分析,并告诉你为了提高网站性能,如何基于某些规则而进行优化。测试个人站点通过测试个人站点可以获得下面的数据23条准则MakefewerHT…

    2022年10月28日
  • c# MD5加密

    c# MD5加密usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Threading.Tasks;/****************************** *概要:MD5加密 *设…

  • LaTeX数学公式-详细教程

    LaTeX数学公式-详细教程LaTeX数学公式,包含前言,注意事项,插入公式,注释,编号,转义字符,换行与对齐,字体,空格,上下标,括号,大括号和行标,分式,开方,对数,省略号,最值,方程组和分段函数,累加和累乘,矢量,积分,极限,导数与偏导,矩阵,表格,希腊字母,运算符,戴帽符号,特殊符号,等等。

发表回复

您的电子邮箱地址不会被公开。

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