码迷,mamicode.com
首页 > Windows程序 > 详细

百度天气API使用测试

时间:2016-06-11 17:11:19      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:

request函数是百度的模板,网址和key也没错,可是返回值啥都没有。。困扰我一天了。。

 1 public class MainActivity extends Activity {
 2     
 3     Button getWeather;
 4     TextView showJson;
 5 
 6     String httpUrl = "http://apis.baidu.com/apistore/weatherservice/weather";
 7     String httpArg = "citypinyin=beijing";
 8     String jsonResult = request(httpUrl, httpArg);
 9 
10     @Override
11     protected void onCreate(Bundle savedInstanceState) {
12         super.onCreate(savedInstanceState);
13         setContentView(R.layout.activity_main);
14 
15         getWeather = (Button) findViewById(R.id.getWeather);
16         ButtonListener listener = new ButtonListener();
17         getWeather.setOnClickListener(listener);
18         showJson = (TextView) findViewById(R.id.showJson);
19         
20     }
21 
22     class ButtonListener implements OnClickListener {
23 
24         @Override
25         public void onClick(View v) {
26             // TODO Auto-generated method stub
27             switch (v.getId()) {
28             case R.id.getWeather:
29 //                Toast.makeText(MainActivity.this, jsonResult.toString(), Toast.LENGTH_SHORT).show();
30 //                if (request(httpUrl, httpArg) == "")
31 //                Log.d("MainActivity", "asdasdasdad");
32 //                else Log.d("MainActivity", request(httpUrl, httpArg));
33                 showJson.setText(request(httpUrl, httpArg));    
34                 break;
35             default:
36                 break;
37         }
38         }
39         
40     }
41 
42     public static String request(String httpUrl, String httpArg) {
43         BufferedReader reader = null;
44         String result = null;
45         StringBuffer sbf = new StringBuffer();
46         httpUrl = httpUrl + "?" + httpArg;
47 
48         try {
49             URL url = new URL(httpUrl);
50             HttpURLConnection connection = (HttpURLConnection) url
51                     .openConnection();
52             connection.setRequestMethod("GET");
53             // 填入apikey到HTTP header
54             connection.setRequestProperty("apikey",  "c71ca21053ffc590e06f324968896823");
55             connection.connect();
56             InputStream is = connection.getInputStream();
57             reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
58             String strRead = null;
59             while ((strRead = reader.readLine()) != null) {
60                 sbf.append(strRead);
61                 sbf.append("\r\n");
62             }
63             reader.close();
64             result = sbf.toString();
65         } catch (Exception e) {
66             e.printStackTrace();
67         }
68         return result;
69     }
70 
71 
72 }

 

百度天气API使用测试

标签:

原文地址:http://www.cnblogs.com/wjg-xx/p/5575418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!