1.网络接口
private final static String SEARCH_LOCATION_ADDRESS = "http://www.yodao.com/smartresult-xml/search.s?type=mobile&q=";
2.查询
try
{
URL url = new URL(SEARCH_LOCATION_ADDRESS + userInput);//包装接口地址
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);//上传数据
InputStream inputStream = httpURLConnection.getInputStream();//获取返回的数据流
InputStreamReader isr = new InputStreamReader(inputStream, "gbk");//一定要在这个地方才不会乱码(utf-8,gb2312)
BufferedReader br = new BufferedReader(isr);//利用BufferedReader将流转为String
String result = "";
String temp;
while((temp = br.readLine()) != null)
{
result = result + temp;
}
String location = "";
location = getStringFromXml(result);//将字符串传递过去,获取位置
Toast toast = Toast.makeText(FindNumberActivity.this, location, Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 0, 0);
toast.show();
System.out.println("查询执行完毕!");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
3.从xml中将需要的标签中的内容解析出来
/**
* 将xml字符串解析出来,返回地点信息
* */
public String getStringFromXml(String str)
{
String result = "";
ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(str.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这个标签
{
result = parser.nextText().toString();//将标签中的内容读取出来,不是getText()!!!
System.out.println("location解析出来啦:" + result);
}
break;
case XmlPullParser.END_TAG:// 结束元素事件
break;
}
eventType = parser.next();
}
}
catch (XmlPullParserException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return result;//将地址返回
}