android之HTTP请求后台数据,GSON解析数据,异步获取数据

android之HTTP请求后台数据

 

	/*
	 * 查询从URL得到的字符串
	 */
	public static String queryStringForGet(String url) {
		// 获取HttpGet对象
		HttpGet request;
		String result = "null";

		try {
			request = new HttpGet(url);
			
			// HttpClient对象// 获得HttpResponse对象
			HttpResponse response = new DefaultHttpClient().execute(request);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 取得返回的数据
				result = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

				//截取所需的字符串,去掉"{"hongshan":["、"]"
				
				System.out.println("result=" + result);
				
				return result;// 返回结果
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一些参考步骤: 1. 首先,您需要在您的应用程序中添加一个用于输入城市名称的文本框和一个按钮,用于触发城市更改操作。您可以使用Android Studio中的布局编辑器来完成这些任务。 2. 创建一个名为“Weather”(或其他您喜欢的名称)的Java类来存储天气数据。在这个类中,您需要定义一个名为“city”的字符串属性,用于存储当前城市的名称。例如: ``` public class Weather { private String city; public String getCity() { return city; } public void setCity(String city) { this.city = city; } } ``` 3. 在您的应用程序中,使用Gson库来解析天气数据。您需要在您的build.gradle文件中添加以下依赖项: ``` implementation 'com.google.code.gson:gson:2.8.6' ``` 4. 在您的应用程序中,创建一个名为“WeatherUtils”的Java类,并添加一个名为“updateWeather”的静态方法,用于更新天气数据。这个方法应该接受一个城市名称作为参数,并使用Gson库从一个天气API获取城市的天气数据。 ``` public class WeatherUtils { public static Weather updateWeather(String cityName) { String apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&appid=YOUR_API_KEY_HERE"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(apiUrl) .build(); try { Response response = client.newCall(request).execute(); String responseData = response.body().string(); Gson gson = new Gson(); Weather weather = gson.fromJson(responseData, Weather.class); weather.setCity(cityName); return weather; } catch (IOException e) { e.printStackTrace(); return null; } } } ``` 5. 在您的应用程序中,当用户点击“更改城市”按钮时,调用“updateWeather”方法以获取新城市的天气数据。例如: ``` String newCityName = ...; // 获取用户输入的新城市名称 Weather newWeather = WeatherUtils.updateWeather(newCityName); ``` 6. 最后,将新的天气数据更新到您的应用程序界面中。例如,您可以将新城市的名称显示在文本框中,并在屏幕上显示新城市的天气预报。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值