HttpClient实现RPC协议
转载请说明出处:https://blog.****.net/LiaoHongHB/article/details/85051935
一、使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接
二、新建工程:rpc-httpclient,子模块:httpclient-api和httpclient-consume
httpclient-api:基于sprint boot的rest接口
UserController:
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUserInfo")
public String getUserInfo(String username) {
userService.getUserInfo(username);
return username;
}
}
UserServiceImpl:
@Service
public class UserServiceImpl implements UserService {
@Override
public void getUserInfo(String username) {
System.out.println("你好," + username);
}
}
httpclient-consume:
引入httpclient依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
ConsumeController:
@RestController
public class ConsumeController {
@RequestMapping("/getUserInfo")
public String getUserInfo(String username) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建httpGet
String url = "http://127.0.0.1:5008/httpclient-api/getUserInfo?username=" + username;
HttpGet httpGet = new HttpGet(url);
System.out.println("URL is " + httpGet.getURI());
CloseableHttpResponse response = null;
try {
//执行http请求
response = httpClient.execute(httpGet);
//获取http响应体
HttpEntity entity = response.getEntity();
System.out.println("-----------------");
//打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response Content Length:" + entity.getContentLength());
String content = EntityUtils.toString(entity);
System.out.println("Response Content:" + content);
return content;
}
System.out.println("------------------");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
response.close();
httpClient.close();
}
return null;
}
}
三、运行及运行效果:
httpclient-api:
httpclient-consume: