一,android调用C#写的WebService,服务端返回的是一个xml格式的数据,只需要解析xml即可!!下面贴出源码
1.就一个Activity,主要实现的功能就是获取布局文件输入传给服务器的值
public class MainActivity extends Activity {
String address = AddressService.getAddress(name,pass);
String result = address.toString();
if (result.equals("true")) {
Toast.makeText(MainActivity.this, "跳转成功", 1).show();
}
textView.setText(address);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), R.string.error, 1).show();
}
}
2.main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
</LinearLayout>
3.服务器返回的数据也就是需要解析xml格式的数据(此段代码是webservice soap1.2服务器返回的xml格式的数据)
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
</soap12:Envelope>
4.使用pull方法解析xml数据(访问网络如果放在主线程里面会报NetWork错误,原因使android4.0以后不可以直接在主线程里面访问网络)
public class AddressService {
*/
public static String getAddress(String name,String pass) throws Exception{
String soap = readSoap();
soap = soap.replaceAll("\$name", name);
soap = soap.replaceAll("\$pass", pass);
byte[] entity = soap.getBytes();
String path = "###############";//API地址也就是webservice的访问地址
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
conn.getOutputStream().write(entity);
if(conn.getResponseCode() == 200){
return parseSOAP(conn.getInputStream());
}
return null;
}
private static String parseSOAP(InputStream xml)throws Exception{
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(xml, "UTF-8");
int event = pullParser.getEventType();
while(event != XmlPullParser.END_DOCUMENT){
switch (event) {
case XmlPullParser.START_TAG:
//此处是pull解析xml由于我的项目返回的是一个boolean值,"logigResult"(截图看)
if("loingResult".equals(pullParser.getName())){
return pullParser.nextText();
}
break;
}
event = pullParser.next();
}
return null;
}
private static String readSoap() throws Exception{
InputStream inStream = AddressService.class.getClassLoader().getResourceAsStream("soap12.xml");
byte[] data = StreamTool.read(inStream);
return new String(data);
}
}
5.工具类
public class StreamTool {
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) != -1){
outputStream.write(buffer, 0, len);
}
inStream.close();
return outputStream.toByteArray();
}
}
截图:
1----------------------------------------
2------------------------------------------------------