HttpClient
用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包–>工具API
举个栗子
package com.jt.test;
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;
/**
* @author Osiris
* @date 2020/12/10 20:18
*/
public class TestHttpClient {
/**
* 实例化HttpClient对象
* 定义远程访问的url地址
* 定义请求类型的对象
* 发起http请求,获得响应结果
* 对返回结果进行校验,获取真实数据信息
*/
@Test
public void testGet() throws IOException {
HttpClient httpClient=HttpClients.createDefault();
String url="http://www.baidu.com";
HttpGet httpGet=new HttpGet(url);
HttpResponse httpResponse=httpClient.execute(httpGet);
//获取状态码
int status=httpResponse.getStatusLine().getStatusCode();
if(status==200){
//获取响应结果
HttpEntity entity=httpResponse.getEntity();
String result= EntityUtils.toString(entity,"UTF-8");
System.out.println(result);
}
}
}
@RequestMapping("testHttpClient")
@ResponseBody
public List<User> testHttpClient(){
return userService.testHttpClient();
}
public interface UserService {
List<User> testHttpClient();
}
@Override
public List<User> testHttpClient() {
/**
* 由jt-web服务器连接jt-sso的服务器
*/
List<User> userList=new ArrayList<>();
//List<User> userList2=new ArrayList<>();
String url="http://sso.jt.com/user/testHttpClient";
HttpClient httpClient=HttpClients.createDefault();
HttpGet httpGet=new HttpGet(url);
try {
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity=httpResponse.getEntity();
String result= EntityUtils.toString(httpEntity,"UTF-8");
userList=ObjectMapperUtil.toObj(result,userList.getClass());
/*for(LinkedHashMap<String,Object> map:userList){
User uerTemp=new User();
uerTemp.setId(Long.parseLong(map.get("id")+""));
}*/
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return userList;
}