前言: 真正的梦想,永远在实现之中,更在坚持之中。累了,就停一停,让手贴着手,温暖冷漠的岁月;苦了,就笑一笑,让心贴着心,体味至爱的抚摸;哭了,就让泪水尽情流淌,痛彻心菲也是精彩。选择一条道路,就选择一种人生一种无悔一种执着。阴霾终会荡尽,狞笑终是无聊,卑鄙终会沉寂。
转载请标明出处:http://blog.csdn.net/android_for_james/article/details/51407697
源码下载地址我放在了文章的最底部
先来看看运行效果图:
一、前期准备
1.我们需要到百度API Store注册成为会员
百度API Store网址为:http://apistore.baidu.com
2.我们需要找到一个叫天气的api
3.点开后我们可以看到进行天气请求的一些帮助文档
4.服务器传回来的数据格式:我们可以看到是Json格式,天气信息保存在retData标签下
二、代码实现
首先我们需要将这个应用规划为三个类,一个主类,一个请求类,一个数据处理类
即:MainActivity,HttpRequestTools,AnalyseTools
1.MainActivity里主要做的事就是获取用户想要查询的城市并显示数据
public class MainActivity extends ActionBarActivity { //注册完成后获取到的apikey private static final String apiKey="你申请得到的apices"; //上传请求的地址信息 private String httpUrl = "http://apis.baidu.com/apistore/weatherservice/cityname"; //用户输入城市名称信息 private String httpArg = null; private Handler handler=null; private EditText cityET; private Button search; private TextView showInfo; private ImageView weatherImg; private String cityName=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); InitEvents(); search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { //注意在api文档中他没有提及直接用汉字传输信息是不行的,这里需要将用户输入的城市信息进行网络编码 //例如北京编码完成后就变成了%E5%8C%97%E4%BA%AC cityName=(String)URLEncoder.encode(cityET.getText().toString(),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } httpArg="cityname="+cityName; //System.out.println(httpArg); //发送获取天气请求 HttpRequestTools httpRequestTools=new HttpRequestTools(httpUrl,httpArg,apiKey,showInfo,weatherImg,handler); httpRequestTools.start(); } }); } public void InitEvents() { cityET=(EditText)findViewById(R.id.city_et); search=(Button)findViewById(R.id.search); showInfo=(TextView)findViewById(R.id.weatherInfo_tv); weatherImg=(ImageView)findViewById(R.id.weatherInfo_img); handler= new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; } }
2.HttpRequestTools,这个类用来提交请求并接收服务器给我们返回的天气数据
public class HttpRequestTools extends Thread{ //因为是网络请求(耗时任务)所以需要在新线程中完成数据的获取,所以这个工具类需要继承自Thread String httpUrl, httpArg ,apikey; TextView show; ImageView weatherImg; Handler handler=null; HttpRequestTools(String httpUrl, String httpArg, String apikey,TextView tv,ImageView weatherImg,Handler handler) { this.httpUrl=httpUrl; this.httpArg=httpArg; this.apikey=apikey; this.show=tv; this.weatherImg=weatherImg; this.handler=handler; } @Override public void run() { super.run(); //用来做数据缓冲 StringBuffer sb=new StringBuffer(); BufferedReader reader=null; String result=null; //安装api组合URL httpUrl=httpUrl+"?"+httpArg; try { URL url= new URL(httpUrl); //向服务器发送获取天气数据请求 HttpURLConnection httpConnection=(HttpURLConnection)url.openConnection(); httpConnection.setRequestMethod("GET"); httpConnection.setRequestProperty("apikey",apikey); httpConnection.connect(); //链接完成后就将数据保存到数据流中,这里是怕回传的数据如果直接按文本输出有可能是乱码,所以这里要重新编码一下 InputStream in=httpConnection.getInputStream(); reader=new BufferedReader(new InputStreamReader(in,"UTF-8")); String str; while((str=reader.readLine())!=null) { sb.append(str + "\n"); } //数据接收完毕,先关闭上次流 reader.close(); //再关闭底层流 in.close(); result=sb.toString(); //回传回来的数据是Json格式我们需要将关键信息提取出来 AnalyseTools analyseTools=new AnalyseTools(result); final String finalResult = analyseTools.AnalyseText(); //System.out.println(finalResult); //更新数据 handler.post(new Runnable() { @Override public void run() { show.setText(finalResult); //按照天气配置图片 if(finalResult.contains("多云")) { weatherImg.setImageResource(R.drawable.cloud); }else if(finalResult.contains("晴")) { weatherImg.setImageResource(R.drawable.sunny); }else if(finalResult.contains("雨")) { weatherImg.setImageResource(R.drawable.rain); }else if(finalResult.contains("阴")) { weatherImg.setImageResource(R.drawable.cloudy); }else if(finalResult.contains("雪")) { weatherImg.setImageResource(R.drawable.snow); } } }); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }3. AnalyseTools这个类用来处理服务器返回的Json格式的数据
public class AnalyseTools { String receiveInfo=null; AnalyseTools(String JsonText) { receiveInfo=JsonText; } public String AnalyseText() { String weatherInfo=null; //先判断一下天气是否获取成功,如果没成功会有errNum:-1提示 if(receiveInfo.contains("\"errNum\":-1")) { weatherInfo="请求天气数据失败,请稍后再试"; } else { try { //使用Json来解析文本数据 JSONObject jsonObject = new JSONObject(receiveInfo); //定位到retData关键词 JSONObject json = (JSONObject) jsonObject.get("retData"); StringBuffer sb = new StringBuffer(); sb.append("城市: " + json.getString("city") + "\n"); sb.append("日期: " + json.getString("date") + "\n"); sb.append("发布时间: " + json.getString("time") + "\n"); sb.append("天气情况: " + json.getString("weather") + "\n"); sb.append("温度: " + json.getString("temp") + "\n"); sb.append("最低气温: " + json.getString("l_tmp") + "\n"); sb.append("最高气温: " + json.getString("h_tmp") + "\n"); sb.append("风向: " + json.getString("WD") + "\n"); sb.append("风力: " + json.getString("WS") + "\n"); sb.append("日出时间: " + json.getString("sunrise") + "\n"); sb.append("日落时间: " + json.getString("sunset") + "\n"); weatherInfo = sb.toString(); } catch (JSONException e) { e.printStackTrace(); } } return weatherInfo; } }
转载请标明出处:http://blog.csdn.net/android_for_james/article/details/51407697
源码下载地址:http://download.csdn.net/detail/android_for_james/9520311
如果对你有帮助,那就顶一下~~~
如果你喜欢我的文章欢迎关注我的博客:http://blog.csdn.net/android_for_james