原文: 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 已定义。
@GET@Path("/users/{id}")public User getUserById (@PathParam("id") Integer id){User user = new User();user.setId(id);user.setFirstName("demo");user.setLastName("user");return user;}@POST@Path("/users")public User addUser(){//Some code}
要使用 Apache httpclient 构建 RESTful 客户端,请遵循以下说明。
1. Apache HttpClient Maven 依赖项
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.1.1</version></dependency>
2. Apache HttpClient GET API 示例
Java 程序,用于如何使用 http get 请求发送 json 数据。
public static void demoGetRESTAPI() throws Exception{DefaultHttpClient httpClient = new DefaultHttpClient();try{//Define a HttpGet request; You can choose between HttpPost, HttpDelete or HttpPut also.//Choice depends on type of method you will be invoking.HttpGet getRequest = new HttpGet("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");//Set the API media type in http accept headergetRequest.addHeader("accept", "application/xml");//Send the request; It will immediately return the response in HttpResponse objectHttpResponse response = httpClient.execute(getRequest);//verify the valid error code firstint statusCode = response.getStatusLine().getStatusCode();if (statusCode != 200){throw new RuntimeException("Failed with HTTP error code : " + statusCode);}//Now pull back the response objectHttpEntity httpEntity = response.getEntity();String apiOutput = EntityUtils.toString(httpEntity);//Lets see what we got from APISystem.out.println(apiOutput); //<user id="10"><firstName>demo</firstName><lastName>user</lastName></user>//In realtime programming, you will need to convert this http response to some java object to re-use it.//Lets see how to jaxb unmarshal the api response contentJAXBContext jaxbContext = JAXBContext.newInstance(User.class);Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));//Verify the populated objectSystem.out.println(user.getId());System.out.println(user.getFirstName());System.out.println(user.getLastName());}finally{//Important: Close the connecthttpClient.getConnectionManager().shutdown();}}
3. 带有 json 正文的 Apache HttpClient POST API 示例
Java 程序,用于如何使用 http post 请求将 json 数据发送到服务器。
public static void demoPostRESTAPI() throws Exception{DefaultHttpClient httpClient = new DefaultHttpClient();User user = new User();user.setId(100);user.setFirstName("Lokesh");user.setLastName("Gupta");StringWriter writer = new StringWriter();JAXBContext jaxbContext = JAXBContext.newInstance(User.class);Marshaller jaxbMarshaller = jaxbContext.createMarshaller();jaxbMarshaller.marshal(user, writer);try{//Define a postRequest requestHttpPost postRequest = new HttpPost("http://localhost:8080/RESTfulDemoApplication/user-management/users");//Set the API media type in http content-type headerpostRequest.addHeader("content-type", "application/xml");//Set the request post bodyStringEntity userEntity = new StringEntity(writer.getBuffer().toString());postRequest.setEntity(userEntity);//Send the request; It will immediately return the response in HttpResponse object if anyHttpResponse response = httpClient.execute(postRequest);//verify the valid error code firstint statusCode = response.getStatusLine().getStatusCode();if (statusCode != 201){throw new RuntimeException("Failed with HTTP error code : " + statusCode);}}finally{//Important: Close the connecthttpClient.getConnectionManager().shutdown();}}
将您对 http GET
和 POST 请求的 httpclient 示例的评论发给我。
学习愉快!
