Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement RPC based on HttpClient in Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how Java implements RPC based on HttpClient. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1 introduction to HttpClient

The basic functions of users' HTTP access are provided under the java.net package in JDK, but it lacks the flexibility or the functions required by many applications.

HttpClient was originally a subproject of Apache Jakarta Common. Used to provide efficient, up-to-date, feature-rich client-side programming toolkits that support the HTTP protocol, and it supports the latest version of the HTTP protocol. It became a top project in 2007.

Popular explanation: HttpClient can be implemented to use Java code to complete standard HTTP requests and responses.

2 code implementation

2.1 Server

Create a new project HttpClientServer

2.1.1 New Controller

Com.mrshun.controller.DemoController@Controllerpublic class DemoController {@ RequestMapping ("/ demo") @ ResponseBody public String demo (String param) {return "demo" + param;}} 2.1.2 New initiator

New initiator

Com.mrshun.HttpClientServerApplication@SpringBootApplicationpublic class HttpClientServerApplication {public static void main (String [] args) {SpringApplication.run (HttpClientServerApplication.class,args);}} 2.2 client

Create a new HttpClientDemo project

2.2.1 add dependencies

Org.apache.httpcomponents httpclient 4.5.10 2.2.2 New Class

Create a new com.mrshun.HttpClientDemo and write the main method.

2.2.2.1 access using the GET method

Public static void main (String [] args) {try {/ / create http tool (understood as: browser) initiates a request and parses the response CloseableHttpClient httpClient = HttpClients.createDefault (); / / request path URIBuilder uriBuilder = new URIBuilder ("http://localhost:8080/demo"); uriBuilder.addParameter (" param "," get123 ") / / create the HttpGet request object HttpGet get = new HttpGet (uriBuilder.build ()); / / create the response object CloseableHttpResponse response = httpClient.execute (get); / / convert the HttpEntity type to the string type and set the character encoding String result = EntityUtils.toString (response.getEntity (), "utf-8") because the response body is a string. / / output result System.out.println (result); / / release resource response.close (); httpClient.close ();} catch (URISyntaxException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();}}

2.2.2.2 access using POST

Public class HttpClientDemo {public static void main (String [] args) {try {/ / create http tool (understood as: browser) initiates a request and parses the response CloseableHttpClient httpClient = HttpClients.createDefault (); / / create the HttpPOST request object HttpPost post = new HttpPost ("http://localhost:8080/demo");") / / all request parameters List params = new ArrayList (); params.add (new BasicNameValuePair ("param", "123")); / / create the object of the text implementation class of the HttpEntity interface, put the parameter and set the code HttpEntity httpEntity = new UrlEncodedFormEntity (params," utf-8 "); / / put post.setEntity (httpEntity) in the HttpPost object / / create the response object CloseableHttpResponse response = httpClient.execute (post); / / because the response body is a string, convert the HttpEntity type to the string type String result = EntityUtils.toString (response.getEntity ()); / / output the result System.out.println (result) / / release resource response.close (); httpClient.close ();} catch (IOException e) {e.printStackTrace ();} 3. Jackson usage

3.1 convert an object to a json string

ObjectMapper objectMapper = new ObjectMapper (); People peo = new People (); objectMapper.writeValueAsString (peo); 3.2 convert json strings to objects

ObjectMapper objectMapper = new ObjectMapper (); People peo = objectMapper.readValue (content, People.class); 3.3 convert json strings to List collections

ObjectMapper objectMapper = new ObjectMapper (); JavaType javaType = objectMapper.getTypeFactory (). ConstructParametricType (List.class, People.class); List list = objectMapper.readValue (content, javaType); 4 HttpClient request contains JSON

4.1 java code implementation

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 controller interface parameters

@ RequestBody converts the stream data in the request body to the specified object. Mostly used when the request parameter is json data and the requested Content-Type= "application/json"

@ RequestMapping ("/ demo4") @ ResponseBodypublic String demo4 (@ RequestBody List list) {System.out.println (list); return list.toString ();} 6 Ajax send json parameters

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)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report