百度天气API使用测试
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了百度天气API使用测试相关的知识,希望对你有一定的参考价值。
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使用测试的主要内容,如果未能解决你的问题,请参考以下文章