前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >接口OkHttp系列(一)- 简介、安装部署、Get请求、Post请求

接口OkHttp系列(一)- 简介、安装部署、Get请求、Post请求

作者头像
wangmcn
发布2022-07-25 17:22:40
1.2K0
发布2022-07-25 17:22:40
举报
文章被收录于专栏:AllTests软件测试

接口OkHttp系列(一)

简介、安装部署、Get请求、Post请求

目录

  • 1、简介
  • 2、安装部署
  • 3、Get请求
    • 3.1、无参数
    • 3.2、有参数(拼接方式)
    • 3.3、有参数(添加参数)
  • 4、Post请求
    • 4.1、无参数
    • 4.2、有参数

1、简介

HTTP是现在主流应用使用的网络请求方式,用来交换数据和内容。OkHttp是一个很棒的适用于Android和Java应用程序的HTTP和HTTP/2客户端,它是一个第三方类库,由移动支付Square公司贡献,这是一个开源项目,用于替代HttpUrlConnection和Apache HttpClient。

官方网址:https://square.github.io/okhttp

官方github地址:https://github.com/square/okhttp

2、安装部署

使用OkHttp需要下载okhttp和okio两个jar包。

下载okhttp:

下载地址:

http://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

下载okio:

下载地址:

http://mvnrepository.com/artifact/com.squareup.okio/okio

本系列篇章okhttp使用okhttp-3.10.0.jar包。

本系列篇章okio使用okio-1.14.0.jar包。

将下载的jar包引用到项目里就可以使用OkHttp了。

由于本系列篇章还会用到Json,所以要下载Json包。

下载Json:

下载地址:

http://mvnrepository.com/artifact/org.json/json

同样将下载的Json包引用到项目里。

本系列篇章接口请求链接使用moco生成。

如图所示:需要用到moco包和Json配置文件(已经配置完成)。

启动moco服务:

命令行进入moco包所在目录。

输入 java -jar moco-runner-0.12.0-standalone.jar http -p 8083 -c mymoco.json

如图所示:moco服务开启,就可以使用接口请求链接了。

3、Get请求

3.1、无参数

1、创建Get类。

没有参数,直接发送请求链接地址。

创建Request对象,使用get方法。

脚本代码:

代码语言:javascript
复制
package com.test.demo;
 
import java.io.IOException;
import java.util.concurrent.TimeUnit;
 
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
 
/**
 * Get请求(没有参数)
 *
 * @author wangmcn
 *
 */
public class Get {
 
       public static void main(String[] args) throws IOException {
 
              final int CONNECT_TIMEOUT = 30;
              final int READ_TIMEOUT = 30;
              final int WRITE_TIMEOUT = 30;
             
              // 创建OkHttpClient对象
              OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // 设置连接超时时间
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) // 设置读超时时间
                            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) // 设置写超时时间
                            .retryOnConnectionFailure(true) // 是否自动重连
                            .build();
 
              // 创建Request对象
              Request request = new Request.Builder()
                            .url("http://localhost:8083/getdemo")
                            .get()
                            .build();
 
              // 得到Response对象
              Response response = client.newCall(request).execute();
             
              if(response.isSuccessful()){
                     System.out.println("获取响应状态: " + response.code());
                     System.out.println("获取响应信息: " + response.message());
                     System.out.println("获取网页源码: " + response.body().string());
              }
             
              // 清除并关闭线程池
              client.dispatcher().executorService().shutdown();
              // 清除并关闭连接池
              client.connectionPool().evictAll();
 
       }
 
}

2、运行结果:

3.2、有参数(拼接方式)

1、创建Get2类。

有参数,请求链接为url(http://localhost:8083/getdemo2)与参数

(?username=admin&password=123456)拼接方式。

创建Request对象,使用get方法。

脚本代码:

代码语言:javascript
复制
package com.test.demo;
 
import java.io.IOException;
import java.util.concurrent.TimeUnit;
 
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
 
/**
 * Get请求(有参数,请求为url与参数拼接方式)
 *
 * @author wangmcn
 *
 */
public class Get2 {
 
       public static void main(String[] args) throws IOException {
 
              final int CONNECT_TIMEOUT = 30;
              final int READ_TIMEOUT = 30;
              final int WRITE_TIMEOUT = 30;
             
              // 创建OkHttpClient对象
              OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // 设置连接超时时间
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) // 设置读超时时间
                            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) // 设置写超时时间
                            .retryOnConnectionFailure(true) // 是否自动重连
                            .build();
 
              // 创建Request对象
              Request request = new Request.Builder()
                            .url("http://localhost:8083/getdemo2?username=admin&password=123456")
                            .get()
                            .build();
             
              // 得到Response对象
              Response response = client.newCall(request).execute();
             
              if(response.isSuccessful()){
                     System.out.println("获取响应状态: " + response.code());
                     System.out.println("获取响应信息: " + response.message());
                     System.out.println("获取网页源码: " + response.body().string());
              }
             
              // 清除并关闭线程池
              client.dispatcher().executorService().shutdown();
              // 清除并关闭连接池
              client.connectionPool().evictAll();
 
       }
 
}

2、运行结果:

3.3、有参数(添加参数)

1、创建Get3类。

有参数,创建HttpUrl对象,添加参数。

创建Request对象,使用get方法。

脚本代码:

代码语言:javascript
复制
package com.test.demo;
 
import java.io.IOException;
import java.util.concurrent.TimeUnit;
 
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
 
/**
 * Get请求(有参数,创建HttpUrl对象,添加参数)
 *
 * @author wangmcn
 *
 */
public class Get3 {
 
       public static void main(String[] args) throws IOException {
 
              final int CONNECT_TIMEOUT = 30;
              final int READ_TIMEOUT = 30;
              final int WRITE_TIMEOUT = 30;
             
              // 创建OkHttpClient对象
              OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // 设置连接超时时间
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) // 设置读超时时间
                            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) // 设置写超时时间
                            .retryOnConnectionFailure(true) // 是否自动重连
                            .build();
             
              // 创建HttpUrl对象,添加参数
              HttpUrl.Builder urlBuilder = HttpUrl.parse("http://localhost:8083/getdemo2").newBuilder();
              urlBuilder.addQueryParameter("username", "admin");
              urlBuilder.addQueryParameter("password", "123456");
             
              // 创建Request对象
              Request request = new Request.Builder()
                            .url(urlBuilder.toString())
                            .get()
                            .build();
             
              // 得到Response对象
              Response response = client.newCall(request).execute();
             
              if(response.isSuccessful()){
                     System.out.println("获取响应状态: " + response.code());
                     System.out.println("获取响应信息: " + response.message());
                     System.out.println("获取网页源码: " + response.body().string());
              }
             
              // 清除并关闭线程池
              client.dispatcher().executorService().shutdown();
              // 清除并关闭连接池
              client.connectionPool().evictAll();
 
       }
 
}

2、运行结果:

4、Post请求

4.1、无参数

1、创建Post类。

创建Request对象,使用post方法。

脚本代码:

代码语言:javascript
复制
package com.test.demo;
 
import java.io.IOException;
import java.util.concurrent.TimeUnit;
 
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
 
/**
 * Post请求(没有参数)
 *
 * @author wangmcn
 *
 */
public class Post {
 
       public static void main(String[] args) throws IOException {
 
              final int CONNECT_TIMEOUT = 30;
              final int READ_TIMEOUT = 30;
              final int WRITE_TIMEOUT = 30;
             
              // 创建OkHttpClient对象
              OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // 设置连接超时时间
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) // 设置读超时时间
                            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) // 设置写超时时间
                            .retryOnConnectionFailure(true) // 是否自动重连
                            .build();
 
              // 创建Request对象
              Request request = new Request.Builder()
                            .url("http://localhost:8083/postdemo")
                            .post(RequestBody.create(null, ""))
                            .build();
             
              // 得到Response对象
              Response response = client.newCall(request).execute();
             
              if(response.isSuccessful()){
                     System.out.println("获取响应状态: " + response.code());
                     System.out.println("获取响应信息: " + response.message());
                     System.out.println("获取网页源码: " + response.body().string());
              }
             
              // 清除并关闭线程池
              client.dispatcher().executorService().shutdown();
              // 清除并关闭连接池
              client.connectionPool().evictAll();
 
       }
 
}

2、运行结果:

4.2、有参数

1、创建Post2类。

创建FormBody对象,添加参数。

创建Request对象,使用post方法。

脚本代码:

代码语言:javascript
复制
package com.test.demo;
 
import java.io.IOException;
import java.util.concurrent.TimeUnit;
 
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
 
/**
 * Post请求(有参数)
 *
 * @author wangmcn
 *
 */
public class Post2 {
 
       public static void main(String[] args) throws IOException {
 
              final int CONNECT_TIMEOUT = 30;
              final int READ_TIMEOUT = 30;
              final int WRITE_TIMEOUT = 30;
             
              // 创建OkHttpClient对象
              OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // 设置连接超时时间
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) // 设置读超时时间
                            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) // 设置写超时时间
                            .retryOnConnectionFailure(true) // 是否自动重连
                            .build();
 
              // 创建FormBody对象,添加参数
              FormBody body = new FormBody.Builder()
                            .add("username", "admin")
                            .add("password", "123456")
                            .build();
 
              // 创建Request对象
              Request request = new Request.Builder()
                            .url("http://localhost:8083/postdemo2")
                            .post(body)
                            .build();
             
              // 得到Response对象
              Response response = client.newCall(request).execute();
             
              if(response.isSuccessful()){
                     System.out.println("获取响应状态: " + response.code());
                     System.out.println("获取响应信息: " + response.message());
                     System.out.println("获取网页源码: " + response.body().string());
              }
             
              // 清除并关闭线程池
              client.dispatcher().executorService().shutdown();
              // 清除并关闭连接池
              client.connectionPool().evictAll();
 
       }
 
}

2、运行结果:

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-04-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 AllTests软件测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 目录
  • 3.1、无参数
  • 3.2、有参数(拼接方式)
  • 3.3、有参数(添加参数)
  • 4.1、无参数
  • 4.2、有参数
相关产品与服务
云支付
云支付(Cloud Pay,CPay)为您提供开放、可靠的聚合收款技术服务和商户管理功能。云支付支持刷卡支付、扫码支付、一码多付多种支付方式。服务商也可使用云支付提供的 SDK 和 HTTPS 接口,将云支付集成进自己的系统中,为商户提供的个性化解决方案。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档