android 和风天气怎么接入 怎么调用

2014年6月 移动开发大版内专家分月排行榜第一2014年3月 移动开发大版内专家分月排行榜第一
2014年11月 移动开发大版内专家分月排行榜第二2014年4月 移动开发大版内专家分月排行榜第二2014年2月 移动开发大版内专家分月排行榜第二
匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。& & &之前做的一个小程序需要获取天气预报接口,使用的是中国天气网的免费接口:
.cn/data/.html ,但最近发现这个接口的天气数据不更新了,最新的天气是日的。推测可能是加了什么限制,目前网上搜到的大部分天气接口都是这个。
& & & 下面的两个天气接口倒是仍然可以使用,不过一个是获取实时天气情况的,一个是获取当天整体天气情况的。对于需要获取7天内的天气情况,还需要找寻其他接口来实现。
.cn/data/sk/.html
.cn/data/cityinfo/.html
& & & &通过这几天的测试,终于找到了一个可用的,特提供给大家。
接口获取的就是中天气网的手机版页面中的数据,网址为:&首页-中国天气网 .cn/index.html。
& & & &数据是通过webclient,get方式来抓取的。这里需要指出一个需要注意的地方。
就是在webClient添加的请求头信息中加入Referer信息,否则获取的天气数据不是当天的。
获取的的数据为:
如果不加Referer头信息,获取到的数据为:
无论你什么时候获取,获取到的都是这天的天气数据。奇怪的是time是最新的,一直在更新的。由此也可以看出来,他们是加了某种过滤机制无法获取真实的当天天气,这也间接解释了为什么上面提到的那个天气接口不能使用了。
说到这里那就再加一句,开头提到的天气接口&.cn/data/.html 即使我加了Referer信息也不能获取当天的。
数据抓取代码:
class Program
//参考文章:中国天气网的数据接口研究 - Create Chen - 博客园 /technology/p/3488176.html
static void Main(string[] args)
//实时天气
// string url = ".cn/data/sk/.html?_=4";
//穿衣指数
string url = ".cn/data/zsM/.html?_=1";
string html = webGetHtml(url);
Console.WriteLine(html);
Console.ReadKey();
public static string webGetHtml(string url)
// string url = "/";
& & & & & & // /babycool
WebClient client = new WebClient();
//设置发出请求 的URI
client.BaseAddress =
//添加到请求头部的信息
//GET / HTTP/1.1
//Accept: text/html, application/xhtml+xml, */*
//Accept-Language: zh-CN
//User-Agent: Mozilla/5.0 ( MSIE 9.0; qdesk 2.4.; Windows NT 6.1; Trident/5.0)
//Accept-Encoding: gzip, deflate
//Connection: Keep-Alive
client.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01");
client.Headers.Add("Accept-Language", "zh-CN,q=0.8");
//注意:Referer 一定要加,否则获取的不是当天的。
client.Headers.Add("Referer", ".cn/");
client.Headers.Add("User-Agent", "Mozilla/5.0 ( MSIE 9.0; Windows NT 6.1;Chrome/27.0.; Trident/5.0)");
//client.Headers.Add("Connection", "Keep-Alive");
//client.Headers.Add("Accept-Encoding", "gzip, deflate");
//如果是获取网站的首页的内容 则为 client.OpenRead("/");
//如果是获取网站域名下的非首页的内容 则为client.OpenRead(url);
//获取流数据
Stream webStream = client.OpenRead(url);
StreamReader reader = new StreamReader(webStream, Encoding.UTF8);
//获取html代码
// string html = reader.ReadToEnd();
return reader.ReadToEnd();
转载请注明出处。
阅读(...) 评论()Android项目之天气预报 的实现分析
输入要查询的城市名称,点击查询按钮后,依次出现七天的天气情况。出现时有动画效果
二、实现过程
(一)获取天气预报数据
1、首先搞定天气预报数据来源的问题,提高天气预报服务的有很多网站,这些网站一般都会提供比较详细的 API 接口供应用程序调用,以聚合数据为例,其官网为:/如下图所示:
点击注册,进入注册界面:
登录成功后,就会进入到如下界面。
点击左侧菜单中我的数据,进入如下界面
点击申请新数据,如下所示,必须实名认证
进入聚合数据首页,选择 API 选项卡,选择免费的天气预报 API
点击进入后,只要申请就送 500 次使用,如下图所示。
复制其中的 AppKey:ab9d7ebaf71fcdc4ba094
打开全国天气预报 API 后,会有一项请求示例,按照其规则拼接字符串后在地址栏中输入
具体参照聚合数据的文档
下面是类的展示
2、编写网络数据访问工具类
首先需要在 uiti 包下定义一个接口,比如将它命名成 HttpCallbackListener,代码如下
package com.example.weather.
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
然后定义 HttpUtil 类,代码如下
package com.example.weather.
import java.io.BufferedR
import java.io.InputS
import java.io.InputStreamR
import java.net.HttpURLC
import java.net.URL;
import android.util.L
public class HttpUtil {
public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
new Thread(new Runnable() {
public void run() {
HttpURLConnection connection =
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(&GET&);
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in = connection.getInputStream();
BufferedReader reader =
new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
if (listener != null) {
// 回调 onFinish()方法
listener.onFinish(response.toString());
} catch (Exception e) {
if (listener != null) {
// 回调 onError()方法
listener.onError(e);
} finally {
if (connection != null) {
connection.disconnect();
}).start();
3、测试一下能否正常访问天气预报接口得到返回的数据
package com.example.weather.
import java.io.UnsupportedEncodingE
import java.net.URLE
import com.example.weather.util.HttpCallbackL
import com.example.weather.util.HttpU
import android.test.TestC
public class WeatherGetTest
extends AndroidTestCase{
public void testGetData(){
String cityN
cityName = URLEncoder.encode(&菏泽&, &utf-8&);
weatherUrl=&/weather/index?format=2&cityname=&+cityName+&&key=ab9d7ebaf71fcdc4ba094&;
HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {
public void onFinish(String response) {
// TODO Auto-generated method stub
System.out.println(response);
public void onError(Exception e) {
// TODO Auto-generated method stub
}catch (Exception e) {
// TODO: handle exception
由于涉及到访问网络,需要在 AndroidManifest.xml 文件中加入访问网络的权限。
(三)UI 设计
activity_weather.xml
activity_weather_listitem.xml
其中 weather_list_layout_animation.xml 文件是一个设置布局动画的,实现过程如下 :
在 res 目录下新建 anim 文件夹, 在其下新建 weather_list_layout_animation.xml 文件, 如下:
weather_list_animation.xml
weather_list_layout_animation.xml
Weather.java
package com.example.weather.
public class Weather {
private String dayOfW//星期几
private S//日期
private S//温度
private S//天气
public Weather(){
public Weather(String dayOfWeek, String date, String temperature,
String weather) {
this.dayOfWeek = dayOfW
this.date =
this.temperature =
this.weather =
public String getDayOfWeek() {
return dayOfW
public void setDayOfWeek(String dayOfWeek) {
this.dayOfWeek = dayOfW
public String getDate() {
public void setDate(String date) {
this.date =
public String getTemperature() {
public void setTemperature(String temperature) {
this.temperature =
public String getWeather() {
public void setWeather(String weather) {
this.weather =
public String toString() {
return &Weather [dayOfWeek=& + dayOfWeek + &, date=& + date
+ &, temperature=& + temperature + &, weather=& + weather + &]&;
在 adapter 包下定义适配器 WeatherAdapter
package com.example.weather.
import java.util.L
import android.content.C
import android.view.LayoutI
import android.view.V
import android.view.ViewG
import android.widget.ArrayA
import android.widget.TextV
import com.example.weather.R;
import com.example.weather.moder.W
* 天气适配器
* @author zhupeng
public class WeatherAdapter extends ArrayAdapter {
private int resourceId;
public WeatherAdapter(Context context, int textViewResourceId,
List objects) {
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;
public View getView(int position, View convertView, ViewGroup viewgroup) {
Weather weather=getItem(position);
ViewHolder viewHolder=
if(convertView==null){
viewHolder=new ViewHolder();
convertView=LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder.tvDayOfWeek=(TextView)
convertView.findViewById(R.id.tvDayofWeek);
viewHolder.tvDate=(TextView) convertView.findViewById(R.id.tvDate);
viewHolder.tvTemperature=(TextView) convertView.findViewById(R.id.tvTemperature);
viewHolder.tvWeather=(TextView) convertView.findViewById(R.id.tvWeather);
convertView.setTag(viewHolder);
viewHolder=(ViewHolder) convertView.getTag();
viewHolder.tvDayOfWeek.setText(weather.getDayOfWeek());
viewHolder.tvDate.setText(weather.getDate());
viewHolder.tvTemperature.setText(weather.getTemperature());
viewHolder.tvWeather.setText(weather.getWeather());
return convertV
private class ViewHolder{
TextView tvDayOfW
TextView tvD
TextView tvT
TextView tvW
WeatherActivity.java
package com.example.
import java.io.UnsupportedEncodingE
import java.net.URLE
import java.util.ArrayL
import java.util.L
import com.example.weather.adapter.WeatherA
import com.example.weather.moder.W
import com.example.weather.util.HttpCallbackL
import com.example.weather.util.HttpU
import com.google.gson.JsonA
import com.google.gson.JsonO
import com.google.gson.JsonP
import android.app.A
import android.os.B
import android.os.H
import android.os.M
import android.view.V
import android.view.View.OnClickL
import android.view.animation.LayoutAnimationC
import android.view.animation.ScaleA
import android.widget.EditT
import android.widget.ImageB
import android.widget.ListV
import android.widget.T
public class WeatherActivity extends Activity {
private EditText ecC
private ImageButton btnQ
private ListView lvFutureW
public static final int SHOW_RESPONSE=1;
private List
private Handler handler=new Handler(){
public void handleMessage(Message msg){
switch (msg.what) {
case SHOW_RESPONSE:
String response=(String )msg.
if(response!=null){
parseWithJSON(response);
WeatherAdapter weatherAdapter=new WeatherAdapter
(WeatherActivity.this,
R.layout.activity_weather_listitem, data);
lvFutureWeather.setAdapter(weatherAdapter);
ScaleAnimation scaleAnimation=new ScaleAnimation(0,1,0,1);
scaleAnimation.setDuration(1000);
LayoutAnimationController animationController
LayoutAnimationController(
scaleAnimation, 0.6f);
lvFutureWeather.setLayoutAnimation(animationController);
private void parseWithJSON(String response) {
// TODO Auto-generated method stub
data=new ArrayList();
JsonParser parser=new JsonParser();//json解析器
JsonObject obj=(JsonObject) parser.parse(response);
//获取返回状态吗
String resultcode=obj.get(&resultcode&).getAsString();
//状态码如果是200说明数据返回成功
if(resultcode!=null&&resultcode.equals(&200&)){
JsonObject resultObj=obj.get(&result&).getAsJsonObject();
JsonArray futureWeatherArray=resultObj.get(&future&).getAsJsonArray();
for(int i=0;i();
private void setListeners(){
btnQuery.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String cityName=ecCity.getText().toString();
cityName = URLEncoder.encode(&菏泽&, &utf-8&); //这里我弄成默认的城市了,如果想根据输入的值进行搜索,,,可以把这句话换成cityName = URLEncoder.encode(cityName, &utf-8&);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
System.out.println(&lvFutureWeather=&+lvFutureWeather);
Toast.makeText(WeatherActivity.this, &success&,
Toast.LENGTH_LONG).show();
String weatherUrl = &/weather/index?format=2&cityname=&+cityName+&&key=ab9d7ebaf71fcdc4ba094&;
Toast.makeText(WeatherActivity.this, &success&+weatherUrl,
Toast.LENGTH_LONG).show();
HttpUtil.sendHttpRequest(weatherUrl, new HttpCallbackListener() {
public void onFinish(String response) {
// TODO Auto-generated method stub
Message message=new Message();
message.what=SHOW_RESPONSE;
//将服务器返回的结果存放到Message中
message.obj=response.toString();
handler.sendMessage(message);
public void onError(Exception e) {
// TODO Auto-generated method stub
System.out.println(&访问失败&);
注意: 在进行查询输入城市名时一定要先改编码格式 列如
cityName = URLEncoder.encode(&菏泽&, &utf-8&);}

我要回帖

更多关于 和风天气 key 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信