原文: https://howtodoinjava.com/resteasy/jax-rs-restful-client-using-apache-httpclient/

我们已经学习了有关构建 RESTful Web 服务的知识。 现在学习构建 JAX-RS REST 客户端以便使用 HttpClient RESTful 客户端来使用 Web 服务。

我将重用为 jaxrs xml 示例编写的代码。

我将访问的 HTTP GET 和 POST REST API 已定义。

  1. @GET
  2. @Path("/users/{id}")
  3. public User getUserById (@PathParam("id") Integer id)
  4. {
  5. User user = new User();
  6. user.setId(id);
  7. user.setFirstName("demo");
  8. user.setLastName("user");
  9. return user;
  10. }
  11. @POST
  12. @Path("/users")
  13. public User addUser()
  14. {
  15. //Some code
  16. }

要使用 Apache httpclient 构建 RESTful 客户端,请遵循以下说明。

1. Apache HttpClient Maven 依赖项

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.1.1</version>
  5. </dependency>

2. Apache HttpClient GET API 示例

Java 程序,用于如何使用 http get 请求发送 json 数据。

  1. public static void demoGetRESTAPI() throws Exception
  2. {
  3. DefaultHttpClient httpClient = new DefaultHttpClient();
  4. try
  5. {
  6. //Define a HttpGet request; You can choose between HttpPost, HttpDelete or HttpPut also.
  7. //Choice depends on type of method you will be invoking.
  8. HttpGet getRequest = new HttpGet("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");
  9. //Set the API media type in http accept header
  10. getRequest.addHeader("accept", "application/xml");
  11. //Send the request; It will immediately return the response in HttpResponse object
  12. HttpResponse response = httpClient.execute(getRequest);
  13. //verify the valid error code first
  14. int statusCode = response.getStatusLine().getStatusCode();
  15. if (statusCode != 200)
  16. {
  17. throw new RuntimeException("Failed with HTTP error code : " + statusCode);
  18. }
  19. //Now pull back the response object
  20. HttpEntity httpEntity = response.getEntity();
  21. String apiOutput = EntityUtils.toString(httpEntity);
  22. //Lets see what we got from API
  23. System.out.println(apiOutput); //<user id="10"><firstName>demo</firstName><lastName>user</lastName></user>
  24. //In realtime programming, you will need to convert this http response to some java object to re-use it.
  25. //Lets see how to jaxb unmarshal the api response content
  26. JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
  27. Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  28. User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));
  29. //Verify the populated object
  30. System.out.println(user.getId());
  31. System.out.println(user.getFirstName());
  32. System.out.println(user.getLastName());
  33. }
  34. finally
  35. {
  36. //Important: Close the connect
  37. httpClient.getConnectionManager().shutdown();
  38. }
  39. }

3. 带有 json 正文的 Apache HttpClient POST API 示例

Java 程序,用于如何使用 http post 请求将 json 数据发送到服务器。

  1. public static void demoPostRESTAPI() throws Exception
  2. {
  3. DefaultHttpClient httpClient = new DefaultHttpClient();
  4. User user = new User();
  5. user.setId(100);
  6. user.setFirstName("Lokesh");
  7. user.setLastName("Gupta");
  8. StringWriter writer = new StringWriter();
  9. JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
  10. Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
  11. jaxbMarshaller.marshal(user, writer);
  12. try
  13. {
  14. //Define a postRequest request
  15. HttpPost postRequest = new HttpPost("http://localhost:8080/RESTfulDemoApplication/user-management/users");
  16. //Set the API media type in http content-type header
  17. postRequest.addHeader("content-type", "application/xml");
  18. //Set the request post body
  19. StringEntity userEntity = new StringEntity(writer.getBuffer().toString());
  20. postRequest.setEntity(userEntity);
  21. //Send the request; It will immediately return the response in HttpResponse object if any
  22. HttpResponse response = httpClient.execute(postRequest);
  23. //verify the valid error code first
  24. int statusCode = response.getStatusLine().getStatusCode();
  25. if (statusCode != 201)
  26. {
  27. throw new RuntimeException("Failed with HTTP error code : " + statusCode);
  28. }
  29. }
  30. finally
  31. {
  32. //Important: Close the connect
  33. httpClient.getConnectionManager().shutdown();
  34. }
  35. }

源码下载

将您对 http GET
和 POST 请求的 httpclient 示例的评论发给我。

学习愉快!