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

接口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方法。

脚本代码:

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方法。

脚本代码:

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方法。

脚本代码:

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方法。

脚本代码:

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方法。

脚本代码:

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、运行结果:

图片

 

 

 

如果您觉得文章还不错,请 点赞、分享、在看、收藏 一下,因为这将是我持续输出更多优质文章的最强动力!

在这里推荐一个我自己创建的软件测试交流群,QQ:642830685,群中会不定期的分享软件测试资源,测试面试题以及测试行业资讯,大家可以在群中积极交流技术,还有大佬为你答疑解惑。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值