学习记录,不喜勿喷
什么是OkHttp
一般在Java平台上,我们会使用Apache HttpClient作为Http客户端,用于发送 HTTP 请求,并对响应进行处理。比如可以使用http客户端与第三方服务(如SSO服务)进行集成,当然还可以爬取网上的数据等。OKHttp与HttpClient类似,也是一个Http客户端,提供了对 HTTP/2 和 SPDY 的支持,并提供了连接池,GZIP 压缩和 HTTP 响应缓存功能。
OkHttp优点
(1)支持HTTP2/SPDY(SPDY是Google开发的基于TCP的传输层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验)
(2)socket自动选择最好路线,并支持自动重连,拥有自动维护的socket连接池,减少握手次数,减少了请求延迟,共享Socket,减少对服务器的请求次数
(3)基于Headers的缓存策略减少重复的网络请求
(4)拥有Interceptors轻松处理请求与响应(自动处理GZip压缩)
OkHttp功能
(1)一般的get请求
(2)一般的post请求
(3)基于Http的文件上传
(4)文件下载
(5)上传下载的进度回调
(6)加载图片
(7)支持请求回调,直接返回对象、对象集合
(8)支持session的保持
(9)支持自签名网站https的访问,提供方法设置下证书就行
(10)支持取消某个请求
测试数据接口
package com.waves.controller; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/dataApi") public class ResponseDataController { @GetMapping("/getData") public Map<String,Object> getData(@RequestParam("pageIndex")String pageIndex){ Map<String,Object> map = new HashMap<>(); map.put("username","小明"); map.put("password","123456"); map.put("age","18"); map.put("endSchool","中国北京大学"); List<Map<String,Object>> list = new ArrayList<>(); list.add(map); Map<String,Object> map2 = new HashMap<>(); map2.put("total",list.size()); map2.put("code",200); map2.put("data",list); return map2; } @PostMapping("/postData") public Map<String,Object> postData(@RequestBody Map<String,Object> params){ Map<String,Object> map = new HashMap<>(); map.put("username","小红"); map.put("password","123456"); map.put("age","18"); map.put("school","中国北京大学"); List<Map<String,Object>> list = new ArrayList<>(); list.add(map); Map<String,Object> map2 = new HashMap<>(); map2.put("total",list.size()); map2.put("code",200); map2.put("data",list); return map2; } }
OkHttp POST请求接口
package com.waves.controller; import com.alibaba.fastjson.JSONObject; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/okHttpApi") public class OkHttpController { @PostMapping("/okHttpPost") public Map<String,Object> okHttpPost(@RequestBody Map<String,Object> params){ try { //json字符串的两种形式 String k = "{\n" + "\t\"pageIndex\": \"1\",\n" + "\t\"pageSize\": \"10\",\n" + "\t\"userName\": \"xiaoming\"\n" + "}"; JSONObject json2 = new JSONObject(); json2.put("pageIndex","1"); json2.put("pageSize","20"); json2.put("userName","xiaoming"); //创建一个OkHttpClient OkHttpClient client = new OkHttpClient(); //设置请求头 MediaType mediaType = MediaType.parse("application/json"); //请求体 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(mediaType,k); //创建一个request Request request = new Request.Builder() .post(requestBody) .url("http://localhost:8080/dataApi/postData") .addHeader("content-type","application/json") .build(); //获得返回 Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); //获取返回值 String responseData = response.body().string(); //将json字符串转为JSONObject JSONObject data = JSONObject.parseObject(responseData); //将jsonObject 转为Map Map<String,Object> map2 = data.toJavaObject(Map.class); return map2; }catch (Exception e){ return new HashMap<>(); } } }
OkHttp GET方式请求接口
@GetMapping("/okHttpGet") public Map<String,Object> okHttpGet(@RequestBody Map<String,Object> params){ try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .get() .url("http://localhost:8080/dataApi/getData?pageIndex=1") // .addHeader("content-type","application/json") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); //获取返回值 String responseData = response.body().string(); //将json字符串转为JSONObject JSONObject data = JSONObject.parseObject(responseData); //将jsonObject 转为Map Map<String,Object> map2 = data.toJavaObject(Map.class); return map2; }catch (Exception e){ return new HashMap<>(); } }
项目所需pom(依赖)
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.waves</groupId> <artifactId>waves_okhttp</artifactId> <version>0.0.1-SNAPSHOT</version> <name>waves_okhttp</name> <description>Okhtp project for Spring Boot</description> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-boot.version>2.3.7.RELEASE</spring-boot.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.72</version> </dependency> <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.3.7.RELEASE</version> <configuration> <mainClass>com.waves.WavesOkhttpApplication</mainClass> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
标签:Map,Java,get,map2,map,import,put,new,post From: https://www.cnblogs.com/wdyjt/p/17524932.html