用HTTP GET调用web service(Java、Groovy两个版本)

下面的网址提供了国内飞机航班时刻表 WEB 服务
http://webservice.webxml.com.cn/webservices/DomesticAirline.asmx

wsdl如下:
http://webservice.webxml.com.cn/webservices/DomesticAirline.asmx?wsdl

调用web service可以采用很多方式 比如axis2、xfire、cxf都可以根据wsdl反向生成客户端代码 简化开发

下面我采用的是http get的方式调用其web service,采用的是HttpClient4
import java.net.URLEncoder; 

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpProtocolParams;

/**
* @author Tony Shen
*
*/
public class DomesticAirlineTest {
public static void main(String[] args) throws Exception{
String url = "/webservices/DomesticAirline.asmx/getDomesticAirlinesTime";
String host = "www.webxml.com.cn";
String param = "startCity="+URLEncoder.encode("北京", "utf-8")+"&lastCity="+URLEncoder.encode("上海", "utf-8")+"&theDate=&userID=";

HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET,"UTF-8");

HttpGet httpget = new HttpGet("http://"+host+url+"?"+param);

ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println(responseBody);
httpclient.getConnectionManager().shutdown();
}
}



Groovy版本,主要使用了groovy的HTTPBuilder,需要这个jar
import groovyx.net.http.HTTPBuilder 
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.TEXT

def url = "/webservices/DomesticAirline.asmx/getDomesticAirlinesTime";
def host = "www.webxml.com.cn";
def param = "startCity="+URLEncoder.encode("北京", "utf-8")+"&lastCity="+URLEncoder.encode("上海", "utf-8")+"&theDate=&userID=";

def http = new HTTPBuilder("http://"+host+url+"?"+param)
http.request(GET,TEXT) {req ->
headers.'User-Agent' = 'Mozilla/5.0'
response.success = { resp,reader ->
println resp
System.out << reader
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值