1.网络接口:
如[urlStr下]:/smartresult-xml/search.s?type=mobile&q=13454522345"
2.返回数据
public String resposeString(String urlStr){
String result = "";
try
{
URL url = new URL(urlStr);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);//上传数据
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setReadTimeout(15000);
InputStream inputStream = httpURLConnection.getInputStream();//获取返回的数据流
InputStreamReader isr = new InputStreamReader(inputStream, "gbk");//一定要在这个地方才不会乱码(utf-8,gb2312)
BufferedReader br = new BufferedReader(isr);//利用BufferedReader将流转为String
String temp;
while((temp = br.readLine()) != null)
{
result = result + temp;
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return result;
}3.解析数据[reposeStr 即2的返回值]
ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(reposeStr.getBytes());
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(tInputStringStream, "UTF-8");
int eventType = 0;
eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
switch (eventType)
{
case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
break;
case XmlPullParser.START_TAG:// 开始元素事件
String name = parser.getName();
if (name.equals("location")) //匹配到location这个标签
{
String result = parser.nextText().toString();//将标签中的内容读取出来,不是getText()!!!
}
else if(name.equals("phonenum")){ //匹配phonenum 这个标签
String result = parser.nextText().toString();//将标签中的内容读取出来,不是getText()!!!
}
break;
case XmlPullParser.END_TAG:// 结束元素事件
break;
}
eventType = parser.next();
}
}
catch (XmlPullParserException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}