`
fengzhizi715
  • 浏览: 159757 次
  • 性别: Icon_minigender_1
  • 来自: 上海 苏州
社区版块
存档分类
最新评论

用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 
    }   
  } 
分享到:
评论
1 楼 di1984HIT 2014-02-04  
血的不错啊,

相关推荐

Global site tag (gtag.js) - Google Analytics