基于Http的RPC实现
1.创建spring boot项目作为接收服务的服务器
1.1导入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.5</version>
</dependency>
</dependencies>
1.2配置启动器
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
1.3创建接收返回的控制层
@Controller
@ResponseBody
public class HttpServerController {
@RequestMapping("demo")
public String demo(String param){
return param+"123";
}
}
2.创建发送请求的服务器(一般的maven项目就可以)
2.1导入依赖
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
2.2发送请求
1.上面发送get请求,下面发送post请求
public class Demo {
@Test
public void test01(){
try {
//创建http工具(理解成:浏览器) 发起请求,解析响应
CloseableHttpClient aDefault = HttpClients.createDefault();
//请求路径
URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/demo");
//创建HttpGet请求对象
HttpGet get = new HttpGet(uriBuilder.build());
//创建响应对象
CloseableHttpResponse execute = aDefault.execute(get);
//由于响应体是字符串,因此把HttpEntity类型转换为字符串类型,并设置字符编码
String s = EntityUtils.toString(execute.getEntity(), "UTF-8");
//输出结果
System.out.println(s);
//释放资源
execute.close();
aDefault.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void test1(){
try {
//创建对象
CloseableHttpClient aDefault = HttpClients.createDefault();
//创建连接
URIBuilder builder = new URIBuilder("http://localhost:8080/demo");
//创建post对象
HttpPost post = new HttpPost(builder.build());
//传递参数
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("param","lisi"));
HttpEntity httpEntity = new UrlEncodedFormEntity(pairs,"utf-8");
post.setEntity(httpEntity);
CloseableHttpResponse execute = aDefault.execute(post);
String s = EntityUtils.toString(execute.getEntity());
System.out.println(s);
execute.close();
aDefault.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
本人是个刚入职的小菜鸡,写下来只是一些随笔,用来自己回顾,很多东西不一定正确,只是我当下自己的理解,请各位大神,有错误的地方可以指出来哈。

浙公网安备 33010602011771号