Java基于HttpClient實(shí)現(xiàn)RPC的示例
1 HttpClient簡(jiǎn)介
在JDK中java.net包下提供了用戶HTTP訪問的基本功能,但是它缺少靈活性或許多應(yīng)用所需要的功能。
HttpClient起初是Apache Jakarta Common 的子項(xiàng)目。用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本。2007年成為頂級(jí)項(xiàng)目。
通俗解釋:HttpClient可以實(shí)現(xiàn)使用Java代碼完成標(biāo)準(zhǔn)HTTP請(qǐng)求及響應(yīng)。
2 代碼實(shí)現(xiàn)
2.1 服務(wù)端
新建項(xiàng)目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 新建啟動(dòng)器
新建啟動(dòng)器
com.mrshun.HttpClientServerApplication
@SpringBootApplication
public class HttpClientServerApplication {
public static void main(String[] args) {
SpringApplication.run(HttpClientServerApplication.class,args);
}
}
2.2 客戶端
新建HttpClientDemo項(xiàng)目
2.2.1 添加依賴
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
</dependencies>
2.2.2 新建類
新建com.mrshun.HttpClientDemo,編寫主方法。
2.2.2.1 使用GET方法訪問
public static void main(String[] args) {
try {
//創(chuàng)建http工具(理解成:瀏覽器) 發(fā)起請(qǐng)求,解析響應(yīng)
CloseableHttpClient httpClient = HttpClients.createDefault();
//請(qǐng)求路徑
URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/demo");
uriBuilder.addParameter("param", "get123");
//創(chuàng)建HttpGet請(qǐng)求對(duì)象
HttpGet get = new HttpGet(uriBuilder.build());
//創(chuàng)建響應(yīng)對(duì)象
CloseableHttpResponse response = httpClient.execute(get);
//由于響應(yīng)體是字符串,因此把HttpEntity類型轉(zhuǎn)換為字符串類型,并設(shè)置字符編碼
String result = EntityUtils.toString(response.getEntity(), "utf-8");
//輸出結(jié)果
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 {
//創(chuàng)建http工具(理解成:瀏覽器) 發(fā)起請(qǐng)求,解析響應(yīng)
CloseableHttpClient httpClient = HttpClients.createDefault();
//創(chuàng)建HttpPOST請(qǐng)求對(duì)象
HttpPost post = new HttpPost("http://localhost:8080/demo");
//所有請(qǐng)求參數(shù)
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param","123"));
//創(chuàng)建HttpEntity接口的文本實(shí)現(xiàn)類的對(duì)象,放入?yún)?shù)并設(shè)置編碼
HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");
//放入到HttpPost對(duì)象中
post.setEntity(httpEntity);
//創(chuàng)建響應(yīng)對(duì)象
CloseableHttpResponse response = httpClient.execute(post);
//由于響應(yīng)體是字符串,因此把HttpEntity類型轉(zhuǎn)換為字符串類型
String result = EntityUtils.toString(response.getEntity());
//輸出結(jié)果
System.out.println(result);
//釋放資源
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. Jackson用法
3.1 把對(duì)象轉(zhuǎn)換為json字符串
ObjectMapper objectMapper = new ObjectMapper(); People peo = new People(); objectMapper.writeValueAsString(peo);
3.2 把json字符串轉(zhuǎn)換為對(duì)象
ObjectMapper objectMapper = new ObjectMapper(); People peo = objectMapper.readValue(content, People.class);
3.3 把json字符串轉(zhuǎn)換為List集合
ObjectMapper objectMapper = new ObjectMapper(); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, People.class); List<People> list = objectMapper.readValue(content, javaType);
4 HttpClient請(qǐng)求包含JSON
4.1 java代碼實(shí)現(xiàn)
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 控制器接口參數(shù)
@RequestBody把請(qǐng)求體中流數(shù)據(jù)轉(zhuǎn)換為指定的對(duì)象。多用在請(qǐng)求參數(shù)是json數(shù)據(jù)且請(qǐng)求的Content-Type=”application/json”
@RequestMapping("/demo4")
@ResponseBody
public String demo4(@RequestBody List<People> list) {
System.out.println(list);
return list.toString();
}
6 Ajax發(fā)送json參數(shù)寫法
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<data.length;i++){
alert(data[i].id +" "+data[i].name);
}
},
contentType:'application/json',//請(qǐng)求體中內(nèi)容類型
dataType:'json',//響應(yīng)內(nèi)容類型。
data:json
});
7 跨域
- 跨域:協(xié)議、ip、端口中只要有一個(gè)不同就是跨域請(qǐng)求。
- 同源策略:瀏覽器默認(rèn)只允許ajax訪問同源(協(xié)議、ip、端口都相同)內(nèi)容。
解決同源策略:
在控制器接口上添加@CrossOrigin。表示允許跨域。本質(zhì)在響應(yīng)頭中添加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<data.length;i++){
alert(data[i].id +" "+data[i].name);
}
},
contentType:'application/json',//請(qǐng)求體中內(nèi)容類型
dataType:'json',//響應(yīng)內(nèi)容類型。
data:json
});
到此這篇關(guān)于Java基于HttpClient實(shí)現(xiàn)RPC的示例的文章就介紹到這了,更多相關(guān)Java HttpClient實(shí)現(xiàn)RPC內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaWeb-WebSocket瀏覽器服務(wù)器雙向通信方式
文章介紹了WebSocket協(xié)議的工作原理和應(yīng)用場(chǎng)景,包括與HTTP的對(duì)比,接著,詳細(xì)介紹了如何在Java中使用WebSocket,包括配置類、服務(wù)編寫和前端頁面的實(shí)現(xiàn)2025-02-02
springboot如何開啟緩存@EnableCaching(使用redis)
在Spring Boot項(xiàng)目中集成Redis主要包括添加依賴到pom.xml、配置application.yml中的Redis連接參數(shù)、編寫配置類、在啟動(dòng)類上添加@EnableCaching注解以及測(cè)試接口的查詢和緩存驗(yàn)證等步驟,首先,需要在pom.xml中添加spring-boot-starter-data-redis依賴2024-11-11
解析Flink內(nèi)核原理與實(shí)現(xiàn)核心抽象
Flink API提供了開發(fā)的接口,此外,為了實(shí)現(xiàn)業(yè)務(wù)邏輯,還必須為開發(fā)者提供自定義業(yè)務(wù)邏輯的能力,下面為大家解析Flink內(nèi)核原理與實(shí)現(xiàn)核心抽象2021-08-08
Java循環(huán)對(duì)bean的屬性進(jìn)行賦值的實(shí)現(xiàn)
本文主要介紹了Java循環(huán)對(duì)bean的屬性進(jìn)行賦值,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08

