socket向指定ip写出数据

  1. 建立socket链接
  2. 准备数据
  3. 写出数据
  4. 接收返回数据
    代码如下:
public class WebServiceClient {
	public static final String ip = "localhost";
	public static final int port = 8081;
	public static final String domain = "/xxx/xxx/service/hzService?wsdl";
	public static final String namespace = "http://ssss.mds.wx.dpns.com/";
	
	public static String wsSocketClient(String method,String param){
		String responseLine=null;
		try{
			Socket socket = new Socket(ip,port);
			socket.setKeepAlive(true);  
			socket.setSoTimeout(15000); 
			System.out.println("服务已经链接");
			OutputStream os = socket.getOutputStream();
			InputStream is = socket.getInputStream();
			StringBuilder content = new StringBuilder();
			content.append("<SOAP-ENV:Envelope ");
			content.append("xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" ");
			content.append("xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" ");
			content.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
			content.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
			content.append("<SOAP-ENV:Body>");
			content.append("<"+method+" xmlns=\""+namespace+"\">");
			content.append("<arg0 xmlns=\"\">");
			content.append(param);
			content.append("</arg0>");
			content.append("</"+method+">");
			content.append("</SOAP-ENV:Body>");
			content.append("</SOAP-ENV:Envelope>");
			
			
			
			StringBuilder sb = new StringBuilder();
			sb.append("POST "+domain+" HTTP/1.1\r\n");
			sb.append("Content-Type:text/xml\r\n");
			sb.append("Host:"+ip+":"+port+"\r\n");
			sb.append("Content-Length:"+content.toString().getBytes("utf-8").length+"\r\n");
			sb.append("\r\n");
			sb.append(content);
			String httpSend = sb.toString();
			os.write(httpSend.getBytes("utf-8"));
			os.flush();
			
			socket.shutdownOutput();
			InputStreamReader ireader = new InputStreamReader(is);
			java.io.BufferedReader breader = new java.io.BufferedReader(ireader);
			StringBuilder res = new StringBuilder();
			while ((responseLine = breader.readLine()) != null) {
				res.append(new String(responseLine.getBytes(),"utf-8"));
			}
			System.out.println(res.indexOf("<return>"));
			if(res.indexOf("<return>") != -1){
				responseLine=res.toString().split("<return>")[1];
				responseLine=responseLine.split("</return>")[0];
			}else{
				responseLine = "{errcode:'服务没起!'}";
			}
			System.out.println("服务已经关闭");
			
		}catch(Exception e){
			e.printStackTrace();
			return responseLine;
		}
		return responseLine;
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值