论坛首页 Web前端技术论坛

用URLConnection传递文件参数,通过SOAP到Webservice

浏览 2959 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-08-04  
需求:使用URLConnection跟Webservice进行交互,其中有一个数据类型是base64Binary,对应到服务端就是byte[]。

PS:实际上就是文件处理

SOAP的请求文本格式
POST /MyService.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/upload"

<?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>
    <upload xmlns="http://tempuri.org/">
      <bs>base64Binary</bs>
    </upload>
  </soap:Body>
</soap:Envelope>


Server端
       public string upload(byte[] bs){
            return "123";//囧
       }


客户端
sun.misc.BASE64Encoder base64Encoder = new BASE64Encoder();
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb
		.append("<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/\">");
sb.append("  <soap:Body>");
sb.append("    <upload xmlns=\"http://tempuri.org/\">");
sb.append("      <bs>");
byte[] bs=FileUtil.getByteArray(new File(""));//取得某个文本的byte数组,具体不写
sb.append(base64Encoder.encode(bs));
sb.append("</bs>");
sb.append("    </upload>");
sb.append("  </soap:Body>");
sb.append("</soap:Envelope>");
URL u = new URL(
		"http://localhost:4638/MyService.asmx");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setConnectTimeout(60000);
conn.setReadTimeout(60000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(sb.toString().length()));
conn.setRequestProperty("SOAPAction", "http://tempuri.org/upload");
conn.setRequestMethod("POST");

OutputStream output = conn.getOutputStream();
if (null != sb) {
	byte[] b = sb.toString().getBytes("utf-8");
	output.write(b, 0, b.length);
}
output.flush();
output.close();

InputStream input = conn.getInputStream();
int c = -1;
while (-1 != (c = input.read())) {
	sb.append((char) c);
}
input.close();
String result = sb.toString().replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll(
		"&quot;", "\"");
System.out.println(result);


中间的尝试过程:
由于一部分是String,一部分是byte数组,所以很是困扰
如果使用new String(byte[] bs)添加条件,会报这个错误
Caused by: com.ctc.wstx.exc.WstxUnexpectedCharException: Illegal character ((CTRL-CHAR, code 17))


如果遍历byte数组,添加每个byte,会报这个错误
java.io.IOException: Invalid header signature; read 0x9EF7F6BDD73DCEE3, expected 0xE11AB1A1E011CFD0

PS:后面的数据不是唯一的,不过就是这样格式的错误


最后发现,byte数组传递时需要转成Base64数据格式
例子如下
normal:This is a Test String
Base64:VGhpcyBpcyBhIFRlc3QgU3RyaW5n


给后人谋求福利~
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics