1 HttpClient简介
在JDK中java.net包下提供了用户HTTP访问的基本功能,但是它缺少灵活性或许多应用所需要的功能。
HttpClient起初是Apache Jakarta Common 的子项目。用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本。2007年成为顶级项目。
通俗解释:HttpClient可以实现使用Java代码完成标准HTTP请求及响应。
2 代码实现
2.1 服务端
新建项目HttpClientServer
2.1.1 新建控制器
com.mrshun.controller.DemoController @Controller public class DemoController { @RequestMapping("/demo") @ResponseBody public String demo(String param){ return "demo"+param; } }
2.1.2 新建启动器
新建启动器
com.mrshun.HttpClientServerApplication @SpringBootApplication public class HttpClientServerApplication { public static void main(String[] args) { SpringApplication.run(HttpClientServerApplication.class,args); } }
2.2 客户端
新建HttpClientDemo项目
2.2.1 添加依赖
org.apache.httpcomponents httpclient 4.5.10
2.2.2 新建类
新建com.mrshun.HttpClientDemo,编写主方法。
2.2.2.1 使用GET方法访问
public static void main(String[] args) { try { //创建http工具(理解成:浏览器) 发起请求,解析响应 CloseableHttpClient httpClient = HttpClients.createDefault(); //请求路径 URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/demo"); uriBuilder.addParameter("param", "get123"); //创建HttpGet请求对象 HttpGet get = new HttpGet(uriBuilder.build()); //创建响应对象 CloseableHttpResponse response = httpClient.execute(get); //由于响应体是字符串,因此把HttpEntity类型转换为字符串类型,并设置字符编码 String result = EntityUtils.toString(response.getEntity(), "utf-8"); //输出结果 System.out.println(result); //释放资源 response.close(); httpClient.close(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
2.2.2.2 使用POST方式访问
public class HttpClientDemo { public static void main(String[] args) { try { //创建http工具(理解成:浏览器) 发起请求,解析响应 CloseableHttpClient httpClient = HttpClients.createDefault(); //创建HttpPOST请求对象 HttpPost post = new HttpPost("http://localhost:8080/demo"); //所有请求参数 Listparams = new ArrayList<>(); params.add(new BasicNameValuePair("param","123")); //创建HttpEntity接口的文本实现类的对象,放入参数并设置编码 HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8"); //放入到HttpPost对象中 post.setEntity(httpEntity); //创建响应对象 CloseableHttpResponse response = httpClient.execute(post); //由于响应体是字符串,因此把HttpEntity类型转换为字符串类型 String result = EntityUtils.toString(response.getEntity()); //输出结果 System.out.println(result); //释放资源 response.close(); httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } }
3. Jackson用法
3.1 把对象转换为json字符串
ObjectMapper objectMapper = new ObjectMapper(); People peo = new People(); objectMapper.writeValueAsString(peo);
3.2 把json字符串转换为对象
ObjectMapper objectMapper = new ObjectMapper(); People peo = objectMapper.readValue(content, People.class);
3.3 把json字符串转换为List集合
ObjectMapper objectMapper = new ObjectMapper(); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, People.class); Listlist = objectMapper.readValue(content, javaType);
4 HttpClient请求包含JSON
4.1 java代码实现
public class HttpClientDemo { public static void main(String[] args) { try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost("http://localhost:8080/demo"); HttpEntity httpEntity= null; String json = "{}"; StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); post.setEntity(entity); CloseableHttpResponse response = httpClient.execute(post); String result = EntityUtils.toString(response.getEntity()); System.out.println(result); response.close(); httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } }
5 控制器接口参数
@RequestBody把请求体中流数据转换为指定的对象。多用在请求参数是json数据且请求的Content-Type=”application/json”
@RequestMapping("/demo4") @ResponseBody public String demo4(@RequestBody Listlist) { System.out.println(list); return list.toString(); }
6 Ajax发送json参数写法
var json = '[{"id":123,"name":"mrshun"},{"id":123,"name":"zhangyongshun"}]'; $.ajax({ url:'/demo5', type:'post', success:function(data){ alert(data); for(var i = 0 ;i
7 跨域
- 跨域:协议、ip、端口中只要有一个不同就是跨域请求。
- 同源策略:浏览器默认只允许ajax访问同源(协议、ip、端口都相同)内容。
解决同源策略:
在控制器接口上添加@CrossOrigin。表示允许跨域。本质在响应头中添加Access-Control-Allow-Origin: *
var json = '[{"id":123,"name":"mrshun"},{"id":456,"name":"zhangyongshun"}]'; $.ajax({ url:'/demo5', type:'post', success:function(data){ alert(data); for(var i = 0 ;i
到此这篇关于Java基于HttpClient实现RPC的示例的文章就介绍到这了,更多相关Java HttpClient实现RPC内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!