restful风格webservice HttpClient方式调用

实例:

服务接口:

package com.webservice.service;

/**
 * Created by oracle on 2016/8/3.
 */
public interface XmlWebservice {
    public String getXmlResponse(String reqXml);
}

服务接口实现类:

package com.webservice.service.impl;

import com.webservice.service.XmlWebservice;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * Created by oracle on 2016/8/3.
 */
@Path("/service")
public class XmlWebserviceImpl implements XmlWebservice {

    @POST
    @Path("/getXmlResponse")
    @Produces("text/xml")
    public String getXmlResponse(String reqXml) {
        System.out.println(reqXml);
        return reqXml;
    }
}

applicationContext-cxf-server.xml

<?xml version="1.0"  encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">


	<context:annotation-config/>

	<jaxrs:server address="/RESTWebService" id="RESTWebService">
		<jaxrs:serviceBeans>
			<bean class="com.webservice.service.impl.XmlWebserviceImpl"></bean>
		</jaxrs:serviceBeans>

		<jaxrs:providers>
			<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
			<bean class="org.apache.cxf.jaxrs.provider.JAXBElementProvider" />
		</jaxrs:providers>
	</jaxrs:server>
	
</beans>



客户端调用:

package com.webservice.client;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.junit.Test;

import java.io.IOException;

/**
 * Created by oracle on 2016/8/3.
 */
public class Client {

    @Test
    public void testWebservice(){
        HttpClient client=new HttpClient();
        String url="http://localhost:8080/webservice/RESTWebService/service/getXmlResponse";
        PostMethod method=new PostMethod(url);
        method.addParameter("param","6");
        try {
            int responseCode=client.executeMethod(method);
            if(responseCode==200){
                String response=method.getResponseBodyAsString();
                System.out.println(response);
            }else{
                System.out.println("无法访问服务接口");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值