您的位置:首页 > 编程语言 > Java开发

java天气预报调用百度接口实现

2016-01-11 17:56 411 查看
package com.cn.weather;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.net.URLEncoder;

public class BaiDu {

//根据城市获取天气信息的java代码

//cityName 是你要取得天气信息的城市的中文名字,如“北京”,“深圳”

static String getWeatherInform(String cityName){

//百度天气API

String baiduUrl = null;

try {

baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+URLEncoder.encode(cityName, "utf-8")+"&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";

} catch (UnsupportedEncodingException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

StringBuffer strBuf;

strBuf = new StringBuffer();

try{

URL url = new URL(baiduUrl);

URLConnection conn = url.openConnection();

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));//转码。

String line = null;

while ((line = reader.readLine()) != null)

strBuf.append(line + " ");

reader.close();

}catch(MalformedURLException e) {

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}

return strBuf.toString();

}

public static void main(String[] args){

BaiDu baidu = new BaiDu();

System.out.println(baidu.getWeatherInform("海淀"));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: