您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關如何在Spring中利用webservice restful對CXF 進行整合,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
webservice restful接口跟soap協議的接口實現大同小異,只是在提供服務的類/接口的注解上存在差異,具體看下面的代碼,然后自己對比下就可以了。
用到的基礎類
User.java
@XmlRootElement(name="User") public class User { private String userName; private String sex; private int age; public User(String userName, String sex, int age) { super(); this.userName = userName; this.sex = sex; this.age = age; } public User() { super(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public static void main(String[] args) throws IOException { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", "192.168.1.20"); System.setProperty("http.proxyPort", "8080"); URL url = new URL("http://www.baidu.com"); URLConnection con =url.openConnection(); System.out.println(con); } }
接下來是服務提供類,PhopuRestfulService.java
@Path("/phopuService") public class PhopuRestfulService { Logger logger = Logger.getLogger(PhopuRestfulServiceImpl.class); @GET @Produces(MediaType.APPLICATION_JSON) //指定返回數據的類型 json字符串 //@Consumes(MediaType.TEXT_PLAIN) //指定請求數據的類型 文本字符串 @Path("/getUser/{userId}") public User getUser(@PathParam("userId")String userId) { this.logger.info("Call getUser() method...."+userId); User user = new User(); user.setUserName("中文"); user.setAge(26); user.setSex("m"); return user; } @POST @Produces(MediaType.APPLICATION_JSON) //指定返回數據的類型 json字符串 //@Consumes(MediaType.TEXT_PLAIN) //指定請求數據的類型 文本字符串 @Path("/getUserPost") public User getUserPost(String userId) { this.logger.info("Call getUserPost() method...."+userId); User user = new User(); user.setUserName("中文"); user.setAge(26); user.setSex("m"); return user; } }
web.xml配置,跟soap協議的接口一樣
<!-- CXF webservice 配置 --> <servlet> <servlet-name>cxf-phopu</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>cxf-phopu</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping>
Spring整合配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <import resource="classpath:/META-INF/cxf/cxf.xml" /> <import resource="classpath:/META-INF/cxf/cxf-servlet.xml" /> <import resource="classpath:/META-INF/cxf/cxf-extension-soap.xml" /> <!-- 配置restful json 解析器 , 用CXF自帶的JSONProvider需要注意以下幾點 -1、dropRootElement 默認為false,則Json格式會將類名作為第一個節點,如{Customer:{"id":123,"name":"John"}},如果配置為true,則Json格式為{"id":123,"name":"John"}。 -2、dropCollectionWrapperElement屬性默認為false,則當遇到Collection時,Json會在集合中將容器中類名作為一個節點,比如{"Customer":{{"id":123,"name":"John"}}},而設置為false,則JSon格式為{{"id":123,"name":"John"}} -3、serializeAsArray屬性默認為false,則當遇到Collecion時,格式為{{"id":123,"name":"John"}},如果設置為true,則格式為[{"id":123,"name":"john"}],而Gson等解析為后者 <bean id="jsonProviders" class="org.apache.cxf.jaxrs.provider.json.JSONProvider"> <property name="dropRootElement" value="true" /> <property name="dropCollectionWrapperElement" value="true" /> <property name="serializeAsArray" value="true" /> </bean> --> <!-- 服務類 --> <bean id="phopuService" class="com.phopu.service.PhopuRestfulService" /> <jaxrs:server id="service" address="/"> <jaxrs:inInterceptors> <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" /> </jaxrs:inInterceptors> <!--serviceBeans:暴露的WebService服務類--> <jaxrs:serviceBeans> <ref bean="phopuService" /> </jaxrs:serviceBeans> <!--支持的協議--> <jaxrs:extensionMappings> <entry key="json" value="application/json"/> <entry key="xml" value="application/xml" /> <entry key="text" value="text/plain" /> </jaxrs:extensionMappings> <!--對象轉換--> <jaxrs:providers> <!-- <ref bean="jsonProviders" /> 這個地方直接用CXF的對象轉換器會存在問題,當接口發布,第一次訪問沒問題,但是在訪問服務就會報錯,等后續在研究下 --> <bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" /> </jaxrs:providers> </jaxrs:server> </beans>
客戶端調用示例:
對于get方式的服務,直接在瀏覽器中輸入http://localhost:8080/phopu/services/phopuService/getUser/101010500 就可以直接看到返回的json字符串
{"userName":"中文","sex":"m","age":26}
客戶端調用代碼如下:
public static void getWeatherPostTest() throws Exception{ String url = "http://localhost:8080/phopu/services/phopuService/getUserPost"; HttpClient httpClient = HttpClients.createSystem(); //HttpGet httpGet = new HttpGet(url); //接口get請求,post not allowed HttpPost httpPost = new HttpPost(url); httpPost.addHeader(CONTENT_TYPE_NAME, "text/plain"); StringEntity se = new StringEntity("101010500"); se.setContentType("text/plain"); httpPost.setEntity(se); HttpResponse response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); log.info("[接口返回狀態嗎] : " + status); String weatherInfo = ClientUtil.getReturnStr(response); log.info("[接口返回信息] : " + weatherInfo); }
客戶端調用返回信息如下:
ClientUtil類是我自己封裝的一個讀取response返回信息的類,encoding是UTF-8
public static String getReturnStr(HttpResponse response) throws Exception { String result = null; BufferedInputStream buffer = new BufferedInputStream(response.getEntity().getContent()); byte[] bytes = new byte[1024]; int line = 0; StringBuilder builder = new StringBuilder(); while ((line = buffer.read(bytes)) != -1) { builder.append(new String(bytes, 0, line, HTTP_SERVER_ENCODING)); } result = builder.toString(); return result; }
看完上述內容,你們對如何在Spring中利用webservice restful對CXF 進行整合有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。