上次已经给大家分享了简单的webservice的使用,提交给服务器的数据只是简单类型的数据,这次呢换成了xml,并通过一个小例子来讲解soap协议的使用。废话就不多说了先来说下xml数据的上传
1.代码的结构没有多大的变化,只需修改一下请求头就可以了,代码如下
//封装数据,数据以byte方式传输
byte[] b=xml.getBytes();
//需要请求的连接
URL url=new URL("http://192.168.87.1:8080/LoginService/LoginWebService");
//打开连接
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//设置请求方式和消息头以及超时时间
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
//设置是否允许对外输出数据
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(b.length));
//取得输出流
OutputStream outPut=conn.getOutputStream();
outPut.write(b);
outPut.flush();
outPut.close();
//判断请求是否成功
if(conn.getResponseCode()==200){
// Log.i();
return "OK";
}else{
return "Err";
}
下面给大家写了点服务器端获取byte数据的代码,顺便在控制台打印xml,这个方法建议写成工具类,我这里就不这样做了
request.setCharacterEncoding("UTF-8");
InputStream in=request.getInputStream();
byte[] b=new byte[1024];
int len=0;
int temp=0;
while((temp=in.read())!=-1){
b[len]=(byte)temp;
len++;
}
System.out.println(new String(b,"UTF-8"));
$number
public String readSoapFile(InputStream input,String number) throws Exception{
byte[] b=new byte[1024];
int len=0;
int temp=0;
while((temp=input.read())!=-1){
b[len]=(byte)temp;
len++;
}
String soapxml=new String(b);
//替换xml文件的占位符
Map map=new HashMap();
map.put("number", number);
return replace(soapxml, map);
}
public String replace(String param,Map params) throws Exception{
//拼凑占位符使用正则表达式替换之
String result=param;
if(params!=null&&!params.isEmpty()){
//拼凑占位符
for(Map.Entry entry:params.entrySet()){
String name="\\$"+entry.getKey();
Pattern p=Pattern.compile(name);
Matcher m=p.matcher(result);
if(m.find()){
result=m.replaceAll(entry.getValue());
}
}
}
return result;
}
public String soapService(InputStream input,String number) throws Exception{
String str="";
String soap=readSoapFile(input,number);
//封装数据,数据以byte方式传输
byte[] b=soap.getBytes();
//需要请求的连接
URL url=new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
//打开连接
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//设置请求方式和消息头以及超时时间
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
//设置是否允许对外输出数据
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(b.length));
//取得输出流
OutputStream outPut=conn.getOutputStream();
outPut.write(b);
outPut.flush();
outPut.close();
//判断请求是否成功
if(conn.getResponseCode()==200){
InputStream in=conn.getInputStream();
byte[] b1=new byte[1024];
int len=0;
int temp=0;
while((temp=in.read())!=-1){
b1[len]=(byte)temp;
len++;
}
str=new String(b1,"UTF-8");
}
return str;
}
UseHttpPost use=new UseHttpPost();
try {
InputStream in=this.getClass().getClassLoader().getResourceAsStream("soap.xml");
use.soapService(in, "13764928990");
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}