web service实验

web service算是软件或者网页里的功能外包了吧,实现过程看起来蛮简单的,但实际挺琐屑的

【实验原理和步骤】

1.实验原理

技术路线:查找并调用股票行情接口,获取股票行情数据,并实现股票行情的图形展示。

2.实现步骤:

(1) 查找和熟悉公开的股票行情数据接口;

(2)基于 Eclipse 开发 Webservice 调用程序;

(3)搭建 WEB 应用框架,开发股票行情的 WEB 图形展示网页;

(4) 部署系统;

(5) 测试系统。

【方案设计】

1) 编写web网页,构建查询页面;

2) 编写client程序,在eclipse上运行,开启一个ServerSocket在端口1234上监听,从web端获取请求后,根据SOAP协议,调用服务器端的web service

3处理服务器端返回的数据,生成图表;

4编写web网页对结果进行展示。

 

Talk is cheap, give me your code.

客户端程序:

  1 import java.io.BufferedReader;
  2 import java.io.DataOutputStream;
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.io.InputStreamReader;
  9 import java.net.ServerSocket;
 10 import java.net.Socket;    
 11 import java.nio.channels.Channels;
 12 import java.nio.channels.FileChannel;
 13 import java.nio.channels.WritableByteChannel;
 14 import org.w3c.dom.NodeList;
 15 
 16 import javax.xml.bind.DatatypeConverter;
 17 import javax.xml.soap.MessageFactory;
 18 import javax.xml.soap.MimeHeaders;
 19 import javax.xml.soap.SOAPBody;
 20 import javax.xml.soap.SOAPConnection;
 21 import javax.xml.soap.SOAPConnectionFactory;
 22 import javax.xml.soap.SOAPElement;
 23 import javax.xml.soap.SOAPEnvelope;
 24 import javax.xml.soap.SOAPMessage;
 25 import javax.xml.soap.SOAPPart;
 26 import javax.xml.transform.Source;
 27 import javax.xml.transform.Transformer;
 28 import javax.xml.transform.TransformerFactory;
 29 import javax.xml.transform.stream.StreamResult;
 30 
 31 /*
 32  * A client to call web service on http://www.webxml.com.cn:80/WebServices/ChinaStockWebService.asmx/ to get the
 33  * information of the stock given by code, and return the web browser with a graph show the information
 34  * 
 35  * @Author alex<[email protected]>
 36  */
 37 public class stock_web_client extends Thread{
 38 
 39     private InputStream fin;
 40     private int PortNum;
 41     private ServerSocket ss;
 42     private Socket soc;
 43     InputStream dis;
 44     DataOutputStream dos;
 45     BufferedReader br;
 46     File f=new File("/home/alex/Documents/abc.html");    //the html to get input
 47     File f2=new File("/home/alex/Documents/aaa.html");  //the html to display the result
 48     File f3=new File("/home/alex/Documents/result.gif");  //the result image
 49     boolean doo=true;
 50     String Server_URI="http://WebXml.com.cn/";
 51     String URL="http://www.webxml.com.cn/WebServices/ChinaStockWebService.asmx";
 52     
 53     public stock_web_client(int port) throws IOException{
 54         System.out.print("Enter the port number: ");
 55         PortNum=port;
 56         ss=new ServerSocket(PortNum);
 57         System.out.println("Client get ready at port "+PortNum+"\nWaiting for connection");
 58 
 59 
 60     }
 61     /**
 62      * Get the file name
 63      */
 64     String getFile(String url){
 65         String file_name;
 66         int a;
 67         a=url.indexOf("/");
 68         file_name=url.substring(a);
 69         a=file_name.indexOf("?");
 70         if(a!=-1)
 71             return "No File";
 72         a=file_name.indexOf(" ");
 73         file_name=file_name.substring(0,a);
 74         return file_name;
 75     }
 76     /*
 77      * Get the what method should call 
 78      */
 79     String getAction(String url){
 80         String act;
 81         if(url==null)return "nothing to do";
 82         int a;
 83         a=url.indexOf("/");
 84         act=url.substring(a);
 85         if(a==-1)return "nothing to do";
 86         a=act.indexOf("?");
 87         if(a==-1)return "nothing to do";
 88         act=act.substring(0,a);
 89         return act;
 90     }
 91     /*
 92      * Get parameter in request, the format of returned string like that,
 93      * ParName=Value&ParName=Value&...&parName=Value  
 94      */
 95     String getParameter(String url){
 96         String pa;
 97         int a;
 98         a=url.indexOf("?");
 99         if(a==-1)return "no parameter";
100         url=url.substring(a+1);
101         a=url.indexOf(" ");
102         pa=url.substring(0,a);
103         return pa;
104     }
105     public boolean getStockImageByteByCode(String code) throws Exception{
106         MessageFactory mf = MessageFactory.newInstance();;
107         SOAPMessage sm=mf.createMessage();        
108         SOAPPart sp=sm.getSOAPPart();
109         SOAPEnvelope se=sp.getEnvelope();
110         se.addNamespaceDeclaration("Server", Server_URI);
111         
112         //Construct SOAP body
113         SOAPBody sb=se.getBody();
114         SOAPElement sbe1=sb.addChildElement("getStockImageByteByCode","Server");
115         sbe1.setAttribute("xmlns", Server_URI);
116         SOAPElement sbe2=sbe1.addChildElement("theStockCode","Server");
117         sbe2.addTextNode(code);
118         
119         //Construst SOAP head
120         MimeHeaders mh=sm.getMimeHeaders();
121         mh.addHeader("SOAPAction", Server_URI+"getStockImageByteByCode");
122         
123         sm.saveChanges();
124         
125         System.out.println("SOAP REQUEST Message: ");
126         sm.writeTo(System.out);
127         
128         get_SOAP_Response(sm);
129         
130         return true;
131     }
132     
133     public void get_SOAP_Response(SOAPMessage sm) throws Exception{
134         SOAPConnectionFactory scf=SOAPConnectionFactory.newInstance();
135         SOAPConnection sc= scf.createConnection();
136         SOAPMessage smr=sc.call(sm,URL);
137         //print the content of the returned message
138         TransformerFactory tf=TransformerFactory.newInstance();
139         Transformer tr=tf.newTransformer();
140         Source sourceContent=smr.getSOAPPart().getContent();
141         System.out.println("\nSOAP RESPONSE Message: ");
142         tr.transform(sourceContent, new StreamResult(System.out));
143         
144         //fetch the imagine content from the message 
145         NodeList jpg=smr.getSOAPBody().getElementsByTagName("getStockImageByteByCodeResult");
146         String abc=jpg.item(0).getTextContent().trim();
147         System.out.print("\n"+abc);
148         
149         //convert byte array to image
150         File image_file=new File("/home/alex/Documents/result.gif");
151         FileOutputStream fos=new FileOutputStream(image_file);
152         byte[] pic=DatatypeConverter.parseBase64Binary(abc);
153         fos.write(pic);
154         fos.close();
155         //ByteArrayInputStream bais = new ByteArrayInputStream(pic_bytes);
156         //BufferedImage bi = ImageIO.read((InputStream) bais);
157         //ImageIO.write(bi, "GIF", image_file);
158         /*
159         Iterator<ImageReader> reads=ImageIO.getImageReadersByFormatName("gif");
160         ByteArrayInputStream bis=new ByteArrayInputStream(temp);
161         ImageReader img_re=reads.next();
162         Object source=bis;
163         ImageInputStream iis=ImageIO.createImageInputStream(source);
164         img_re.setInput(iis,true);
165         ImageReadParam irp=img_re.getDefaultReadParam();
166         
167         Image image=img_re.read(0,irp);
168         BufferedImage bfi=new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_RGB);
169         
170         Graphics2D gra=bfi.createGraphics();
171         gra.drawImage(image, null, null);
172         
173         ImageIO.write(bfi, "gif", image_file);
174 */
175         //return smr;
176         
177     }
178     
179     public void run(){
180 
181         try {
182 
183             while(true){
184             soc=ss.accept();
185             dis=soc.getInputStream();
186             dos=new DataOutputStream(soc.getOutputStream());
187             BufferedReader brr=new BufferedReader(new InputStreamReader(dis));
188             //byte[] ch=new byte[(int)f.length()];
189             fin=new FileInputStream(f);
190             String write=brr.readLine();
191             //int k=0;
192             //while(!write.endsWith("</html>")&&k<7){
193                 //k++;
194                 //if(write.startsWith("POST /abc.aa")){
195                     //while(true){
196                         //System.out.println(String.valueOf(write));
197                         //write=brr.readLine();
198                     //}
199                 //}
200             System.out.println("\ncomes from the web: "+write);
201             String act=getAction(write);
202             System.out.println(act);
203             String pa=getParameter(write);
204             System.out.println(pa);
205             String fn=getFile(write);
206             System.out.println(fn);
207             
208             //write=brr.readLine();
209             //if(fn.equalsIgnoreCase("/result.gif")){
210                 //FileInputStream ffin=new FileInputStream(f2);
211                 //BufferedReader bbr=new BufferedReader(new InputStreamReader(ffin));
212                 // return the html to display the image
213                 /*byte[] img_bytes=Files.readAllBytes(f2.toPath());
214                 dos.write(img_bytes);
215                 dos.flush();
216                 //ffin.close();
217                 soc.close();
218                 dos.close();
219                 //bbr.close();*/
220             /*    FileChannel in=new FileInputStream (f2).getChannel();
221                 WritableByteChannel out=Channels.newChannel(soc.getOutputStream());
222                 in.transferTo(0, f2.length(), out);
223                 //stop the client process
224                 break;
225             }*/
226             //Once got the input from user, then process the reques
227             if(act.equalsIgnoreCase("/getStockImageByteByCode"))
228                 if(getStockImageByteByCode(pa.substring(pa.indexOf("=")+1))){
229                     FileInputStream ffin=new FileInputStream(f2);
230                     BufferedReader bbr=new BufferedReader(new InputStreamReader(ffin));
231                     dos.writeBytes("HTTP/1.1 200 OK \r\nConnection: close\r\nServer: Alex‘s Server \r\nContent-Type: text/html\r\n\r\n");
232 
233                     // return the html to display the image
234                     do{
235                         write=bbr.readLine();
236                         dos.writeBytes(write+"\r\n");
237                     }while(!write.equalsIgnoreCase("</html>"));
238 
239                     //this.sleep(40000);
240                     dos.flush();
241                     ffin.close();
242                     //soc.close();
243                     //dos.close();
244                     bbr.close();
245                     //stop the client process
246                     break;
247                 }
248             
249             //System.out.println(String.valueOf(write));
250             //}
251             //ch=fin.read();
252             dos.writeBytes("HTTP/1.1 200 OK \r\nConnection: close\r\nServer: Alex‘s Server \r\nContent-Type: text/html\r\n\r\n");
253             InputStreamReader is=new InputStreamReader(fin);
254             br=new BufferedReader(is);
255             do{
256                 write=br.readLine();
257                 dos.writeBytes(write+"\r\n");
258                 //System.out.println(write);
259                 //aaa++;
260                 //System.out.print(aaa);
261             }while(!write.equalsIgnoreCase("</html>"));
262             if(doo==true)doo=false;
263             //System.out.println(brr.readLine());
264             //dos.write(ch, 0, ch.length);
265             //}while(ch!=-1);
266             dos.flush();
267             
268             fin.close();
269             soc.close();
270             dos.close();
271             //*/
272         }
273             
274             
275        
276             } catch (Exception e) {
277                 e.printStackTrace();
278             }
279     
280         
281     }
282 
283     public static void main(String[] args){
284         //HttpServer hs=HttpServer.create(new InetSocketAddress(1234), 1);
285         try {
286             stock_web_client swc=new stock_web_client(1234);
287             swc.start();
288         } catch (IOException e) {
289             e.printStackTrace();
290         }
291             }
292 }
stock_web_client

获取输入页面:

 1 <html>
 2     <head>
 3         <title>get Stock Image By Code</title>
 4     <head>
 5 
 6     <body>
 7         <h1>This is the post page.</h1>
 8 <form target="_blank" action=‘getStockImageByteByCode‘ method="GET">
 9 
10   <label> enter the stock code and the client will return a image of this stock </label>
11   <p>
12   
13     <span>
14       <input class="frmInput" type="text" size="30" name="theStockCode">
15     </span>
16   
17     <span>
18       <input type="submit" value="submit" class="button">
19     </span>
20   
21   </p>
22 
23 </form>
24 
25    </body>
26 </html>
abc.html

成果展示页面:

1 <html><head><meta http-equiv="Content-Type" content="text/html; charset=GBK">
2 <title> image of the search result </title>
3 <h1>This is the image returned by the search on the server</h1>
4 <img src="file://localhost/home/alex/Documents/result.gif"  alt="result"></img>
5 </html>
aaa.html

 

 

 

这下面英文文档是关于创建web service的,在这次实验里基本没用到,但当时觉得这些说得很细,所以就存了下来,哪天让我写个web service时,就能参考了。

Requirements of a JAX-WS Endpoint

JAX-WS endpoints must follow these requirements:

  • The implementing class must be annotated with either the javax.jws.WebService or javax.jws.WebServiceProvider annotation.
  • The implementing class may explicitly reference an SEI through the endpointInterface element of the @WebService annotation, but is not required to do so. If no endpointInterface is not specified in @WebService, an SEI is implicityly defined for the implementing class.
  • The business methods of the implementing class must be public, and must not be declared static or final.
  • Business methods that are exposed to web service clients must be annotated with javax.jws.WebMethod.
  • Business methods that are exposed to web service clients must have JAX-B-compatible parameters and return types. See Default Data Type Bindings.
  • The implementing class must not be declared final and must not be abstract.
  • The implementing class must have a default public constructor.
  • The implementing class must not define the finalize method.
  • The implementing class may use the javax.annotation.PostConstruct or javax.annotation.PreDestroy annotations on its methods for lifecycle event callbacks.

 

很犯懒,基本都是实验报告里的东西复制粘贴过来的。。。

这个实验耗费了我整整3天时间,这个过程就是不断绕弯路,不断自己爬回来的过程,代码推倒重写三遍以上,过程中学到的东西不少,本想多些点自己这两天这里面学到的细节细活,凌晨4点了,算了=。=

web service实验,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。