OkHttp简介

时间:2022-04-21 00:04:19

什么是OKHttp

一般在Java平台上,我们会使用Apache HttpClient作为Http客户端,用于发送 HTTP 请求,并对响应进行处理。比如可以使用http客户端与第三方服务(如SSO服务)进行集成,当然还可以爬取网上的数据等。OKHttp与HttpClient类似,也是一个Http客户端,提供了对 HTTP/2 和 SPDY 的支持,并提供了连接池,GZIP 压缩和 HTTP 响应缓存功能;

官网:http://square.github.io/okhttp/

添加依赖

在Java中使用OKHttp很简单,如果是maven工程,往pom.xml添加如下xml片段即可,目前最新版本2.7.5

<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.7.5</version>
</dependency>

如果是gradle,添加如下依赖

compile group: 'com.squareup.okhttp', name: 'okhttp', version: '2.7.5'

简单使用

后端Controller

一个简单的spring mvc web应用。

    @RequestMapping(value = "/getUserList", produces = "application/json; charset=utf-8")
@ResponseBody
public String getUserList(int pageNo, int pageSize)
{
Map<String, Object> map = new HashMap<String, Object>();
try
{
Map<String, Object> param = new HashMap<String, Object>();
param.put("pageNo", pageNo);
param.put("pageSize", pageSize);
List<User> userList = userService.queryAll(param);
map.put("userList", userList);
return gson.toJson(map);
}
catch (Exception e)
{
logger.error(e.toString(), e);
}
return gson.toJson(FAILD);
}

使用OkHttp发送Ge请求

package cn.hdu.edu.okhttpdemo;

import java.io.IOException;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response; /**
* Hello world!
*
*/
public class App
{
public String run(OkHttpClient client, String url) throws IOException {
Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute();
return response.body().string();
}
public static void main( String[] args )
{
OkHttpClient client = new OkHttpClient();
try
{
String res = new App().run(client, "http://localhost:8080/webbf/user/getUserList.do?pageNo=0&pageSize=10");
System.out.println(res);
}
catch (IOException e)
{
e.printStackTrace();
} }
}

使用OkHttp发送Post请求

package cn.hdu.edu.okhttpdemo;

import java.io.IOException;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response; /**
* Hello world!
*
*/
public class App
{
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); public String post(OkHttpClient client, String url) throws IOException
{
Request request = new Request.Builder()
.url(url)
.post(new FormEncodingBuilder()
.add("pageNo", "0") //参数1
.add("pageSize", "10") //参数二
.build())
.build();
Response response = client.newCall(request).execute();
return response.body().string();
} public static void main(String[] args)
{
OkHttpClient client = new OkHttpClient();
try
{
String res = new App().post(client,
"http://localhost:8080/webbf/user/getUserList.do");
System.out.println(res);
}
catch (IOException e)
{
e.printStackTrace();
} }
}

结果打印

请求成功,打印以下数据:

{"userList":[{"id":49,"name":"876","address":"876"},{"id":50,"name":"antd","address":"antd"},{"id":51,"name":"sda","address":"sadsd"},{"id":52,"name":"5545","address":"4646546546"},{"id":53,"name":"sdas","address":"sdasa"},{"id":54,"name":"hggs","address":"sdsd"},{"id":55,"name":"4","address":"5"},{"id":56,"name":"4","address":"4"},{"id":57,"name":"00ba9d8e-0628-4477-857f-ef617c1ff4bc","address":"5906"},{"id":58,"name":"613ee3a3-fb87-4413-a8e0-9272d10ad4a7","address":"6427"}]}