HttpClient介绍
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.5 .6(2015-09-11)
SpringCloud跨域中实现远程数据访问底层实现就是httpClient.
httpClient作用: 在java代码内部发起http请求.
HttpClient 入门案例
package com.jt;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class TestHttpClient {
/**
* 业务需求:在java代码中访问百度的页面
* url: http://www.baidu.com html代码片段
* 实现步骤:
* 1. 获取httpClient对象
* 2. 自定义url地址
* 3. 定义请求类型
* 4. 发起请求 获取响应结果.
* 5. 校验返回值状态,是否正确
* 6. 获取返回值信息,之后完成后续业务处理.
* SDK......
* */
@Test
void Test01(){
HttpClient httpclient = new HttpClient();
String url = "https://www.baidu.com";
HttpGet get = new HttpGet(url);
try{
HttpResponse httpReponse = httpclient.execute(get);
//获取返回值状态 200 为正常
int status = httpResponse.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity entity = httpResponse.getEntity();//获取响应对象的实体信息
//将实体对象转化为用户能够识别的字符串
String result = EntityUtils.toString(entity,"UTF-8");
System.out.println(result);
}else{
System.out.println("httpClient 调用异常");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
====================================================
@Test
public void test01() throws ClientProtocolException, IOException{
CloseableHttpClient httpClient = HttpClients.createDefault(); //创建HTTPClient的实例
String url = "https://item.jd.com/5236335.html?dist=jd"; //定义访问IP
HttpPost httpPost = new HttpPost(url); //设定请求
CloseableHttpResponse response = httpClient.execute(httpPost); //获取response对象
String html = EntityUtils.toString(response.getEntity()); //获取页面信息
System.out.println(html);
}
@Test
public void testGet() throws ClientProtocolException, IOException{
//定义httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
String uri = "https://item.jd.com/5236335.html?dist=jd";
HttpGet httpGet = new HttpGet(uri);
//获取请求的全部参数 GET https://item.jd.com/5236335.html?dist=jd HTTP/1.1
RequestLine requestLine = httpGet.getRequestLine();
//获取请求方式 GET/POST
requestLine.getMethod();
//获取浏览器 http协议 HTTP/1.1
requestLine.getProtocolVersion();
//请求 uri:https://item.jd.com/5236335.html?dist=jd
requestLine.getUri();
//获取HTTP响应
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200){
System.out.println("获取请成功");
//获取HTML
String html = EntityUtils.toString(httpResponse.getEntity());
System.out.println(html);
}
}
httpClient 高级案例
业务说明
用户通过 http://www.jt.com/user/httpClient/saveUser/{username}/{password} 访问服务器.要求利用httpClient技术将用户信息保存到jt-sso中.
发送url请求路径: http://sso.jt.com/user/httpClient/saveUser?username=xxxx&password=xxxx
实现数据传递.
在jt-sso中完成数据入库操作.
编辑jt-web Controller
package com.jt.controller;
import com.jt.pojo.User;
import com.jt.service.HttpClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController //学习httpCLient调用规范
public class HttpClientController {
@Autuwired
private HttpClientService httpClientService;
/**
* 用户测试路径:
* http://www.jt.com/user/httpClient/saveUser/admin123456/123456789
* 将数据传递给sso.jt.com
* return "用户请求成功"
*/
@RequestMapping("/user/httpClient/saveUser/{username}/{password}")
public String saveUser(User user){ //参数接受与对象的属性必须保持一致,可以自动赋值 springmvc
httpClientService.saveUser(user);
return "httpClient测试成功!!!";
}
}
编辑jt-web Service
package com.jt.service;
import com.jt.pojo.User;
import com.jt.unit.ObjectMapperUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
public class HttpClientServiceImpl implements HttpClientService{
//位置jt-web 不能直接链接数据库 需要将数据传递给sso.jt.com
@Override
public void saveUser(User user){
//String userJSON = ObjectMapperUtil.toJSON(user);
String url = "http://sso.jt.com/user/httpClient/saveUser?username="
+user.getUsername()+"&password="+user.getPassword();
//get
HttpClient httpClient = HttpClient.createDefault();
HttpGet httpGet = new HttpGet(url);
try{
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() != 200){
throw new RuntimeException("请求错误");
}
}catch(IOException e){
e.printStackTrace();
Throw new RuntimeException("请求错误");
}
}
}
编辑jt-sso Controller
/**
* 完成httpClient测试
* url:http://sso.jt.com/user/httpClient/saveUser?username=111&password="2222"
*/
@RequestMapping("/httpClient/saveUser")
public SysResult saveUser(User user){
userService.saveHttpCleint(user);
return SysResult.success();
}
编辑 jt-sso Service
@Override
public void saveHttpCleint(User userPOJO) {
userPOJO.setEmail("111222333@qq.com") //数据库中要求email和phone是非空的 暂时写死
.setPhone("1311112222");
userMapper.insert(userPOJO);
}
pojo 对象
package com.jt.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;
@TableName("tb_user")
@Data
@Accessors(chain = true)
public class User extends BasePojo{
@TableId(type = IdType.AUTO)
private Long id;
private String username;
private String password;
private String phone;
private String email;
}