這篇文章給大家分享的是有關Java基于HttpClient如何實現RPC的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
在JDK中java.net包下提供了用戶HTTP訪問的基本功能,但是它缺少靈活性或許多應用所需要的功能。
HttpClient起初是Apache Jakarta Common 的子項目。用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,并且它支持 HTTP 協議最新的版本。2007年成為頂級項目。
通俗解釋:HttpClient可以實現使用Java代碼完成標準HTTP請求及響應。
新建項目HttpClientServer
com.mrshun.controller.DemoController
@Controller
public class DemoController {
@RequestMapping("/demo")
@ResponseBody
public String demo(String param){
return "demo"+param;
}
}新建啟動器
com.mrshun.HttpClientServerApplication
@SpringBootApplication
public class HttpClientServerApplication {
public static void main(String[] args) {
SpringApplication.run(HttpClientServerApplication.class,args);
}
}新建HttpClientDemo項目
<dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.10</version> </dependency> </dependencies>
新建com.mrshun.HttpClientDemo,編寫主方法。
2.2.2.1 使用GET方法訪問
public static void main(String[] args) {
try {
//創建http工具(理解成:瀏覽器) 發起請求,解析響應
CloseableHttpClient httpClient = HttpClients.createDefault();
//請求路徑
URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/demo");
uriBuilder.addParameter("param", "get123");
//創建HttpGet請求對象
HttpGet get = new HttpGet(uriBuilder.build());
//創建響應對象
CloseableHttpResponse response = httpClient.execute(get);
//由于響應體是字符串,因此把HttpEntity類型轉換為字符串類型,并設置字符編碼
String result = EntityUtils.toString(response.getEntity(), "utf-8");
//輸出結果
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 {
//創建http工具(理解成:瀏覽器) 發起請求,解析響應
CloseableHttpClient httpClient = HttpClients.createDefault();
//創建HttpPOST請求對象
HttpPost post = new HttpPost("http://localhost:8080/demo");
//所有請求參數
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param","123"));
//創建HttpEntity接口的文本實現類的對象,放入參數并設置編碼
HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");
//放入到HttpPost對象中
post.setEntity(httpEntity);
//創建響應對象
CloseableHttpResponse response = httpClient.execute(post);
//由于響應體是字符串,因此把HttpEntity類型轉換為字符串類型
String result = EntityUtils.toString(response.getEntity());
//輸出結果
System.out.println(result);
//釋放資源
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}ObjectMapper objectMapper = new ObjectMapper(); People peo = new People(); objectMapper.writeValueAsString(peo);
ObjectMapper objectMapper = new ObjectMapper(); People peo = objectMapper.readValue(content, People.class);
ObjectMapper objectMapper = new ObjectMapper(); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, People.class); List<People> list = objectMapper.readValue(content, javaType);
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();
}
}
}@RequestBody把請求體中流數據轉換為指定的對象。多用在請求參數是json數據且請求的Content-Type=”application/json”
@RequestMapping("/demo4")
@ResponseBody
public String demo4(@RequestBody List<People> list) {
System.out.println(list);
return list.toString();
}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',//請求體中內容類型
dataType:'json',//響應內容類型。
data:json
});跨域:協議、ip、端口中只要有一個不同就是跨域請求。
同源策略:瀏覽器默認只允許ajax訪問同源(協議、ip、端口都相同)內容。
解決同源策略:
在控制器接口上添加@CrossOrigin。表示允許跨域。本質在響應頭中添加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',//請求體中內容類型
dataType:'json',//響應內容類型。
data:json
});感謝各位的閱讀!關于“Java基于HttpClient如何實現RPC”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。