百度

java URL实现调用其他系统发送报文并获取返回数据

 

    模拟本系统通过Url方式发送报文到目标服务器,并获取返回数据:(实现类)

 1 import java.io.BufferedOutputStream;
 2 import java.io.BufferedReader;
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.io.OutputStream;
 6 import java.io.OutputStreamWriter;
 7 import java.net.URL;
 8 import java.net.URLConnection;
 9 
10 public class BlazeSao {
11 
12     public static void callBlaze(String url ,String data) throws Exception{
13         URL u = new URL(url);
14         System.out.println("建立链接....");
15         //获取连接对象
16         URLConnection uc = u.openConnection();
17         uc.setDoOutput(true);
18         //获取输出流对象
19         OutputStream raw = uc.getOutputStream();
20         OutputStream buffered = new BufferedOutputStream(raw);
21         OutputStreamWriter out = new OutputStreamWriter(buffered, "UTF-8");
22 
23         System.out.println("发送报文:"+data);
24         out.write(data);
25 
26         out.flush();
27         System.out.println("关闭连接");
28         out.close();
29         //获取到返回数据的输入流
30         InputStream is = uc.getInputStream();
31         BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
32         String line = "";
33         StringBuffer blzRspXml = new StringBuffer();
34         System.out.println("获取返回数据:");
35         while((line = br.readLine()) != null){
36             //读取返回数据,分行读取
37             System.out.println(line.trim());
38             blzRspXml.append(line.trim());
39         }
40     }
41 
42     public static void main(String args[]){
43         
44         //目标服务器地址
45         String url1 = "http://10.14.30.242:9080/RES/Rule";
46         //发送的报文
47         String data1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><CardRequest><SEQ_TIME_STAMP>2014325170152799504</SEQ_TIME_STAMP><TYPE>1</TYPE><v_101>-999998</v_101><v_102>0.002740</v_102><v_109>111.11</v_109></CardRequest>";
48         try {
49             BlazeSao.callBlaze(url1,data1);
50         } catch (Exception e) {
51             e.printStackTrace();
52         }
53     }
54 
55 }

输出日志:

建立链接....
发送报文:<?xml version="1.0" encoding="UTF-8"?><CardRequest><SEQ_TIME_STAMP>2014325170152799504</SEQ_TIME_STAMP><TYPE>1</TYPE><v_101>-999998</v_101><v_102>0.002740</v_102><v_109>111.11</v_109><v_110>111.11</v_110</CardRequest>
关闭连接
获取返回数据:
<ResponseData>
<R_001>S5=-9999.0</R_001>
<R_002>T</R_002>
<R_003>Y</R_003>
<R_004></R_004>
<R_005></R_005>
<R_006>S5_B017_others</R_006>
</ResponseData>

 

posted @ 2016-06-08 11:03  雪季28  阅读(4740)  评论(0编辑  收藏  举报
百度