java socket调用webservice以及如何解决连接重置报错问题
2017-12-13 00:08
441 查看
一、写这篇记录的原因:
最近看了一些关于关于socket模拟文件服务器的文章或者视频,客户端通过浏览器访问,服务端通过socket去实现,学习之下了解到就是向socket发送制定格式的内容【http协议】,然后服务端进行解析,返回相关的数据,于是就想肯定要可以使用socket模拟调用webservice【webservice就是http协议+soap报文通过tcp协议来传输】,当然了使用httpclient去模拟发送get/post请求最方便,不过也是自己对http协议深入理解【原来的理解就知道http协议是什么样的,但是具体发送的啥内容也模糊】
二、直接贴代码:
调用部分
package com.pjf.netbase;
import com.pjf.netentity.Response; import com.pjf.netservice.ClientService;
public class WebServiceClient { public final static int BYTELEN = 1024;// 经测试64个字节以上没有问题
public static void main(String[] args) throws Exception {
}
2.Response对象定义
package com.pjf.netentity;
import java.util.HashMap; import java.util.Iterator; import java.util.Map;
/* * @author pengjf 作为调用webservice的返回对象封装 * */ public class Response { private String status;// 状态 private String statusNum; private String version;
= headMap; }
3.socket调用webservice以及返回数据的处理【整个调用以及处理的核心】
package com.pjf.netservice;
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException;
import com.pjf.netentity.Response;
public class ClientService { public static int BYTELEN = 1024; public static Response callWebService(String head,String request,String host,int port) throws UnknownHostException, IOException{
Socket socket = new Socket(host, port); PrintWriter pw = new PrintWriter(socket.getOutputStream()); pw.println(head + request); pw.flush(); Response res=praseInputStrem(socket); pw.close(); pw=null; return res; }
}
三、测试结果:
OK 200 HTTP/1.1
Server–>Microsoft-IIS/6.0
Cache-Control–>private, max-age=0
X-AspNet-Version–>2.0.50727
Content-Length–>838
Date–>Tue, 12 Dec 2017 15
X-Powered-By–>ASP.NET
Content-Type–>text/xml; charset=utf-8
最近看了一些关于关于socket模拟文件服务器的文章或者视频,客户端通过浏览器访问,服务端通过socket去实现,学习之下了解到就是向socket发送制定格式的内容【http协议】,然后服务端进行解析,返回相关的数据,于是就想肯定要可以使用socket模拟调用webservice【webservice就是http协议+soap报文通过tcp协议来传输】,当然了使用httpclient去模拟发送get/post请求最方便,不过也是自己对http协议深入理解【原来的理解就知道http协议是什么样的,但是具体发送的啥内容也模糊】
二、直接贴代码:
调用部分
package com.pjf.netbase;
import com.pjf.netentity.Response; import com.pjf.netservice.ClientService;
public class WebServiceClient { public final static int BYTELEN = 1024;// 经测试64个字节以上没有问题
public static void main(String[] args) throws Exception {
long startTime = System.currentTimeMillis(); String req = /* * "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + */ "<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/\">\r\n" + "<soap:Body>\r\n" + "<getSupportCity xmlns=\"http://WebXml.com.cn/\">\r\n" + "<byProvinceName>安徽</byProvinceName>\r\n" + "</getSupportCity>\r\n" + "</soap:Body>\r\n" + "</soap:Envelope>\r\n"; String head = "POST /WebServices/WeatherWebService.asmx HTTP/1.1\r\n" + "Host: www.webxml.com.cn\r\n" + "Content-Type: text/xml; charset=utf-8\r\n" + "Content-Length:" + req.getBytes().length + "\r\n" + "SOAPAction: \"http://WebXml.com.cn/getSupportCity\"\r\n\r\n"; Response res=ClientService.callWebService(head, req, "www.webxml.com.cn", 80); if(res.getStatus().equals("999")){ System.out.println("连接异常,请检查连接"); }else{ System.out.println(res.toString()); } }
}
2.Response对象定义
package com.pjf.netentity;
import java.util.HashMap; import java.util.Iterator; import java.util.Map;
/* * @author pengjf 作为调用webservice的返回对象封装 * */ public class Response { private String status;// 状态 private String statusNum; private String version;
public Response() { status = "-999"; } public String getStatusNum() { return statusNum; } public void setStatusNum(String statusNum) { this.statusNum = statusNum; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } private Map<String, String> headMap = new HashMap<String, String>();// 头节点 private String resultSoapXml = "";// 解析内容 public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Map<String, String> getHeadMap() { return headMap; } public void setHeadMap(Map<String, String> headMap) { this.headMap
= headMap; }
public String getResultSoapXml() { return resultSoapXml; } public void setResultSoapXml(String resultSoapXml) { this.resultSoapXml = resultSoapXml; } @Override public String toString() { String result = ""; Iterator iter = headMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); result += entry.getKey() + "-->" + entry.getValue() + "\r\n"; } return status + " " + statusNum + " " + version + "\r\n" + result + "\r\n" + resultSoapXml; } }
3.socket调用webservice以及返回数据的处理【整个调用以及处理的核心】
package com.pjf.netservice;
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException;
import com.pjf.netentity.Response;
public class ClientService { public static int BYTELEN = 1024; public static Response callWebService(String head,String request,String host,int port) throws UnknownHostException, IOException{
Socket socket = new Socket(host, port); PrintWriter pw = new PrintWriter(socket.getOutputStream()); pw.println(head + request); pw.flush(); Response res=praseInputStrem(socket); pw.close(); pw=null; return res; }
public static Response praseInputStrem(Socket socket) { Response res = new Response(); try { long startTime = System.currentTimeMillis(); // 接受客户端的响应 byte[] b = new byte[BYTELEN]; byte[] context = null; byte[] headbyte = null; InputStream is = socket.getInputStream(); int len = 0; int start_position = 0; int end_position = 0; int contlen = 0; boolean isContinue = true; boolean isFirstLine=true; while ((len = is.read(b)) != -1) { System.out.println("每次读取的长度:" + len); // 解析内容 if (isContinue) { // 针对头部信息,防止制定的字节一个byte[len]你不够,此处进行字节数组拼接 if (headbyte == null) { headbyte = new byte[len]; System.arraycopy(b, 0, headbyte, 0, len); } else { byte[] tmp = new byte[headbyte.length + len]; System.arraycopy(headbyte, 0, tmp, 0, headbyte.length); System.arraycopy(b, 0, tmp, headbyte.length, len); headbyte = tmp; b = tmp; } for (int i = start_position; i < b.length; i++) { if (b[i] == '\r') { end_position = i; String data = new String(b, start_position, end_position - start_position); if (isFirstLine) { isFirstLine=false; System.out.println(data); String[] firstLineData = data.trim().split(" "); if (firstLineData.length != 3) { res.setStatus("999"); return res; } else { res.setStatus(firstLineData[2]); res.setStatusNum(firstLineData[1]); res.setVersion(firstLineData[0]); } } // String data = new String(b, start_position, // end_position - start_position); if (data.contains("Content-Length")) { // System.out.println("----contlen"+data); contlen = Integer.parseInt(data.split(" ")[1]); } if(data.contains(":")){ String[] headsplit = data.split(":"); res.getHeadMap().put(headsplit[0].trim(),headsplit[1].trim()); } System.out.println("每次读取输出的内容:" + data); start_position = i + 2; i = i + 1; if (data.equals("")) { isContinue = false; System.out.println("内容准备读取,跳出循环准备全部去读"); break; } } } } // 如果头结点已经读取完毕,则进行保留内存的内容结点 if (isContinue == false) { 4000 if (context == null) { context = new byte[b.length - start_position]; if (b.length - start_position > 0) { System.arraycopy(b, start_position, context, 0, b.length - start_position); } // 需要判断是否立即结束 ----针对于一次读完的情况,加入此判断,否则可能存在问题 if (len < BYTELEN) { break; } } else { byte[] tmp = new byte[context.length + len]; System.arraycopy(context, 0, tmp, 0, context.length); System.arraycopy(b, 0, tmp, context.length, len); context = tmp; System.out.println((context.length) + "-------------" + contlen); if (context.length == contlen) {// 表示数据读取完毕 break; } } } } long endTime = System.currentTimeMillis(); System.out.println("使用时间:" + (endTime - startTime)); res.setResultSoapXml(new String(context)); socket.shutdownInput(); socket.shutdownOutput(); is.close(); is = null; socket = null; System.out.println("处理完毕"); } catch (IOException e) { System.out.println(e); } return res; }
}
三、测试结果:
OK 200 HTTP/1.1
Server–>Microsoft-IIS/6.0
Cache-Control–>private, max-age=0
X-AspNet-Version–>2.0.50727
Content-Length–>838
Date–>Tue, 12 Dec 2017 15
X-Powered-By–>ASP.NET
Content-Type–>text/xml; charset=utf-8
相关文章推荐
- java socket调用webservice以及如何解决连接重置报错问题
- (转)jquery跨域调用webService,以及解决跨域情况下只能返回XMl格式数据的问题
- 非托管C++调用 Webservice,如何解决状态保持的问题
- Marvell交换机luaCLI引擎启动流程以及如何解决函数cpssInitSystem()被二次调用的问题
- Java调用.Net WebService问题,以及参数为空解决办法
- 如何解决xfire调用cxf的webservice问题
- Android如何调用webservice 以及错误解决汇总
- 【库连接问题】makefile中如何连接库以及解决/usr/bin/ld: skipping incompatible问题
- 关于ORACLE的ora-12505报错以及连接问题的解决及相关资料
- windows下如何解决PHP调用的外部程序超时阻塞问题
- 如何解决移动应用中 PeekMessage 调用的资源利用问题
- 如何用dot net连接MySQL,及中文乱码问题解决
- 解决Ruby调用带中文参数的WebService的问题。
- 如何解决WebService参数传递中文的问题
- 解决php soap webservice 用c++ soap调用的问题
- 如何解决2000中的连接问题
- Dephi调用C#编写的WebService的一些问题与解决方法
- 如何有效解决C与C++的相互调用问题
- 新手求助:测试连接MYSQL时提示如下,请教问题出在哪?如何解决?
- 错误代码:WLTC0032W ibatis作为持久层,websphere 报告连接没有提交错误,问题的解决以及产生的原因