Webservice调用笔记,获取天气情况
程序员文章站
2022-07-13 12:09:33
...
String proxyHost = "172.16.25.1"; int port = 3128; String soapRequestData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + " <soap:Body>" + " <getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">" + " <theCityName>长沙</theCityName>" + " </getWeatherbyCityName>" + "</soap:Body>" + "</soap:Envelope>"; //然后定义一个PostMethod,这时需要指定web服务的Url; PostMethod postMethod = new PostMethod("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"); HostConfiguration vHostConfiguration = new HostConfiguration(); vHostConfiguration.setProxy(proxyHost, port); //然后把Soap请求数据添加到PostMethod中 byte[] b = soapRequestData.getBytes("UTF-8"); InputStream is = new ByteArrayInputStream(b,0,b.length); postMethod.setRequestHeader("Content-Type", "text/xml;charset=UTF-8"); postMethod.setRequestHeader("SOAPAction","http://WebXml.com.cn/getWeatherbyCityName"); RequestEntity re = new InputStreamRequestEntity(is,"UTF-8"); postMethod.setRequestEntity(re); // 最后生成一个HttpClient对象,并发出postMethod请求 HttpClient httpClient = new HttpClient(); int statusCode = httpClient.executeMethod(vHostConfiguration,postMethod); System.out.println("-------调用完成------,状态码:"+statusCode); if(statusCode==200) { InputStream anXml = postMethod.getResponseBodyAsStream(); StringBuffer response = new StringBuffer(); java.io.ByteArrayOutputStream bs = new ByteArrayOutputStream(); java.io.BufferedOutputStream out = new BufferedOutputStream(bs); byte[] c= new byte[1024]; int len = 0; while ((len = anXml.read(c))>=0) { out.write(c, 0, len); } out.flush(); anXml.close(); System.out.println(bs.toString(postMethod.getRequestCharSet())); } System.exit(0);