Java调用webService示例
1 package com; 2 3 import java.io.ByteArrayInputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.UnsupportedEncodingException; 7 8 import org.apache.commons.httpclient.HttpClient; 9 import org.apache.commons.httpclient.HttpException; 10 import org.apache.commons.httpclient.methods.InputStreamRequestEntity; 11 import org.apache.commons.httpclient.methods.PostMethod; 12 import org.apache.commons.httpclient.methods.RequestEntity; 13 /** 14 * 判断qq是否在线 15 * 输入参数:QQ号码 String,默认QQ号码:8698053。 16 * 返回数据:String,Y = 在线;N = 离线;E = QQ号码错误;A = 商业用户验证失败;V = 免费用户超过数量 17 * @author Spenser 18 * 19 */ 20 public class CheckqqOnline { 21 /** 22 * 23 * @param code qq号码 24 * @return 状态 25 */ 26 public static String infoShow(String code){ 27 //soap的请求数据,可以借助soapUI工具生成 28 String soapRequestData="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " + 29 "xmlns:web=\"http://WebXml.com.cn/\"><soapenv:Header/><soapenv:Body><web:qqCheckOnline><web:qqCode>" 30 +code+"</web:qqCode></web:qqCheckOnline></soapenv:Body></soapenv:Envelope>"; 31 //定义一个PostMethod,需要制定webService服务的URL 32 PostMethod postMethod=new PostMethod("http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx"); 33 //当请求数据中包含头文件的时候加上下行 34 // postMethod.addRequestHeader("SOAPAction",""); 35 //将请求数据已字节的形式加入到PostMethod中 36 byte[] b=null; 37 try { 38 b = soapRequestData.getBytes("utf-8"); 39 } catch (UnsupportedEncodingException e) { 40 e.printStackTrace(); 41 } 42 InputStream is = new ByteArrayInputStream(b,0,b.length); 43 RequestEntity re = new InputStreamRequestEntity(is,b.length,"text/xml; charset=utf-8"); 44 postMethod.setRequestEntity(re); 45 //最后生成一个HttpClient对象,并发出postMethod请求 46 HttpClient httpClient = new HttpClient(); 47 try { 48 int statusCode = httpClient.executeMethod(postMethod); 49 System.out.println(statusCode); 50 } catch (HttpException e) { 51 e.printStackTrace(); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } 55 try { 56 soapRequestData = postMethod.getResponseBodyAsString(); 57 } catch (IOException e) { 58 e.printStackTrace(); 59 } 60 return soapRequestData; 61 } 62 public static void main(String[] args) { 63 String re=infoShow(""); 64 String str=re.substring(re.indexOf("<qqCheckOnlineResult>")+21, re.indexOf("</qqCheckOnlineResult>")); 65 System.out.println("webservice返回的数据: "+re); 66 System.out.println("解析过后的数据: "+str); 67 68 } 69 }
在这边补充一下需要导入的jar包,commons-httpclient-3.1.jar,commons-codec-1.3.jar,commons-logging.jar,本人开始就导入第一个jar包,总是报错,然后发现第一个jar包里的类用到了后面2个jar包!