Android 数据存储
2010-04-10 04:46:00 来源:WEB开发网< uses-permission Android:name="Android.permission.INTERNET" / >
(2)以HTTP POST的方式发送(注意:SERVER_URL并不是指WSDL的URL,而是服务本身的URL)。实现的代码如下所示:
private static final String SERVER_URL = "http://www.webservicex.net/WeatherForecast. asmx/GetWeatherByZipCode"; //定义需要获取的内容来源地址
HttpPost request = new HttpPost(SERVER_URL); //根据内容来源地址创建一个Http请求
// 添加一个变量
List < NameValuePair> params = new ArrayList < NameValuePair>();
// 设置一个华盛顿区号
params.add(new BasicNameValuePair("ZipCode", "200120")); //添加必须的参数
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); //设置参数的编码
try {
HttpResponse httpResponse = new DefaultHttpClient().execute(request); //发送请求并获取反馈
// 解析返回的内容
if(httpResponse.getStatusLine().getStatusCode() != 404)
{
String result = EntityUtils.toString(httpResponse.getEntity());
Log.d(LOG_TAG, result);
}
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage());
}
代码解释:
如上代码使用Http从webservicex获取ZipCode为 “200120”(美国WASHINGTON D.C)的内容,其返回的内容如下:
< WeatherForecasts xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http: //www.w3.org/2001/XMLSchema-instance" xmlns="http://www.webservicex.net">
< Latitude>38.97571< /Latitude>
< Longitude>77.02825< /Longitude>
< AllocationFactor>0.024849< /AllocationFactor>
< FipsCode>11< /FipsCode>
< PlaceName>WASHINGTON< /PlaceName>
< StateCode>DC< /StateCode>
< Details>
< WeatherData>
< Day>Saturday, April 25, 2009< /Day>
更多精彩
赞助商链接