An example of Java implementing RPC based on HttpClient
- 2021-11-29 07:13:00
- OfStack
2.1. 1 New controller
2.1. 2 New Starter
2.2 Client
2.2. 1 Adding dependencies
2.2. 2 New class
3. Usage of Jackson 3.1 Convert Object to json String
3.2 Converting an json string to an object
3.3 Converting an json string to an List set
4 HttpClient request contains JSON 4.1 java code implementation
5 Controller Interface Parameters 6 Ajax sending json parameter writing 7 Cross-domain
1 Introduction to HttpClient
The java. net package in JDK provides the basic functions for users to access HTTP, but it lacks flexibility or functions required by many applications.
HttpClient was originally a subproject of Apache Jakarta Common. Used to provide an efficient, up-to-date, feature-rich client programming kit that supports the HTTP protocol, and it supports the latest version of the HTTP protocol. It became the top project in 2007.
Popular explanation: HttpClient can use Java code to complete the standard HTTP request and response.
2 code implementation
2.1 Server side
New project HttpClientServer
2.1. 1 New controller
com.mrshun.controller.DemoController
@Controller
public class DemoController {
@RequestMapping("/demo")
@ResponseBody
public String demo(String param){
return "demo"+param;
}
}
2.1. 2 New Starter
New starter
com.mrshun.HttpClientServerApplication
@SpringBootApplication
public class HttpClientServerApplication {
public static void main(String[] args) {
SpringApplication.run(HttpClientServerApplication.class,args);
}
}
2.2 Client
New HttpClientDemo project
2.2. 1 Adding dependencies
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
</dependencies>
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 Tools (understood as : Browser) Initiate the request and parse the response
CloseableHttpClient httpClient = HttpClients.createDefault();
// Request path
URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/demo");
uriBuilder.addParameter("param", "get123");
// Create HttpGet Request object
HttpGet get = new HttpGet(uriBuilder.build());
// Create a response object
CloseableHttpResponse response = httpClient.execute(get);
// Since the response body is a string, the HttpEntity Type to a string type and set the character encoding
String result = EntityUtils.toString(response.getEntity(), "utf-8");
// Output result
System.out.println(result);
// Release resources
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 Tools (understood as : Browser) Initiate the request and parse the response
CloseableHttpClient httpClient = HttpClients.createDefault();
// Create HttpPOST Request object
HttpPost post = new HttpPost("http://localhost:8080/demo");
// All request parameters
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param","123"));
// Create HttpEntity The text of the interface implements the object of the class, puts the parameters and sets the encoding
HttpEntity httpEntity = new UrlEncodedFormEntity(params,"utf-8");
// Put into HttpPost Object
post.setEntity(httpEntity);
// Create a response object
CloseableHttpResponse response = httpClient.execute(post);
// Since the response body is a string, the HttpEntity Type to string type
String result = EntityUtils.toString(response.getEntity());
// Output result
System.out.println(result);
// Release resources
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. Usage of Jackson
3.1 Convert Object to json String
ObjectMapper objectMapper = new ObjectMapper();
People peo = new People();
objectMapper.writeValueAsString(peo);
3.2 Converting an json string to an object
ObjectMapper objectMapper = new ObjectMapper();
People peo = objectMapper.readValue(content, People.class);
3.3 Converting an json string to an List set
ObjectMapper objectMapper = new ObjectMapper();
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, People.class);
List<People> 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. Used when the request parameter is json data and the requested Content-Type= "application/json"
@RequestMapping("/demo4")
@ResponseBody
public String demo4(@RequestBody List<People> list) {
System.out.println(list);
return list.toString();
}
6 Ajax sending json parameter writing
com.mrshun.HttpClientServerApplication
@SpringBootApplication
public class HttpClientServerApplication {
public static void main(String[] args) {
SpringApplication.run(HttpClientServerApplication.class,args);
}
}
0
7 Cross-domain
Cross-domain: Protocol, ip, as long as there is one difference in the port, it is a cross-domain request.
Homologous policy: By default, browsers only allow ajax to access homologous (protocol, ip, port all the same) content.
Solve homology strategy:
Add @ CrossOrigin on the controller interface. Indicates that cross-domains are allowed. Essentially add Access-Control-Allow-Origin to the response header: *
com.mrshun.HttpClientServerApplication
@SpringBootApplication
public class HttpClientServerApplication {
public static void main(String[] args) {
SpringApplication.run(HttpClientServerApplication.class,args);
}
}
1