java-根据城市得到当前天气


最近记录一下可能常用的得到天气问题


package com.web.wxutils;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class PublicMethods {

	private static Logger log = Logger.getLogger(PublicMethods.class);

	public static void main(String[] args) throws Exception {
		System.out.println(getWeatherByHttp("深圳"));
		System.out.println(getWeatherByHttp("上海"));
	}

	// 获取天气预报
	public static float getWeatherByHttp(String city) {
		String url = "http://wthrcdn.etouch.cn/weather_mini?";
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("city", city));
		String param = URLEncodedUtils.format(params, "utf-8");
		HttpGet httpGet = new HttpGet(url + param);
		HttpClient httpClient = new DefaultHttpClient();

		HttpResponse httpResponse = null;
		float low = 0;
		try {
			httpResponse = httpClient.execute(httpGet);
			String result = getJsonStringFromGZIP(httpResponse);// 获取到解压缩之后的字符串
			// System.out.println(result);
			// 输出
			JSONObject jsonObject = JSONObject.fromObject(result);
			JSONObject jsonData = jsonObject.getJSONObject("data");
			String forecast = jsonData.getString("forecast");
			JSONArray array = JSONArray.fromObject(forecast);
			String json = array.getString(0);
			JSONObject Object = JSONObject.fromObject(json);

			String Slow = Object.getString("low");
			low = NumberUtils.toFloat(Slow.substring(2, Slow.length() - 1).trim(), 0);// 最低温
			// String Shigh = Object.getString("high");// float
			// high=NumberUtils.toFloat(Shigh.substring(2,Shigh.length()-1).trim(), 0);//最高温
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return low;
	}

	private static String getJsonStringFromGZIP(HttpResponse response) {
		String jsonString = null;
		try {
			InputStream is = response.getEntity().getContent();
			BufferedInputStream bis = new BufferedInputStream(is);
			bis.mark(2);
			// 取前两个字节
			byte[] header = new byte[2];
			int result = bis.read(header);
			// reset输入流到开始位置
			bis.reset();
			// 判断是否是GZIP格式
			int headerData = getShort(header);
			if (result != -1 && headerData == 0x1f8b) {
				is = new GZIPInputStream(bis);
			} else {
				is = bis;
			}
			InputStreamReader reader = new InputStreamReader(is, "utf-8");
			char[] data = new char[100];
			int readSize;
			StringBuffer sb = new StringBuffer();
			while ((readSize = reader.read(data)) > 0) {
				sb.append(data, 0, readSize);
			}
			jsonString = sb.toString();
			bis.close();
			reader.close();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return jsonString;
	}

	private static int getShort(byte[] data) {
		return (int) ((data[0] << 8) | data[1] & 0xFF);
	}
}





  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您可以使用第三方的天气API来获取当前天气信息。以下是使用Java后端获取当前天气的一种方法: 1. 首先,您需要找到一个可用的天气API供应商,并注册一个账号来获取API密钥。一些常用的天气API供应商包括:OpenWeatherMap、WeatherAPI、和AccuWeather等。 2. 使用Java的网络请求库(如OkHttp或HttpClient)发送HTTP请求到天气API的接口,并传递必要的参数,如城市称或经纬度。 3. 解析API返回的JSON数据,提取您所需的天气信息,如温度、天气状况、湿度等。 以下是一个简单的示例代码,使用OpenWeatherMap API获取当前天气: ```java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.json.JSONObject; public class WeatherApiClient { private static final String API_KEY = "YOUR_API_KEY"; private static final String API_URL = "https://api.openweathermap.org/data/2.5/weather"; public static void main(String[] args) { String city = "Beijing"; // 替换为您需要查询的城市称 try { OkHttpClient client = new OkHttpClient(); String url = API_URL + "?q=" + city + "&appid=" + API_KEY; Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String responseData = response.body().string(); JSONObject json = new JSONObject(responseData); double temperature = json.getJSONObject("main").getDouble("temp"); int humidity = json.getJSONObject("main").getInt("humidity"); String weatherDescription = json.getJSONArray("weather").getJSONObject(0).getString("description"); System.out.println("Temperature: " + temperature); System.out.println("Humidity: " + humidity); System.out.println("Weather: " + weatherDescription); } else { System.out.println("Error: " + response.code() + " - " + response.message()); } } catch (Exception e) { e.printStackTrace(); } } } ``` 请注意,您需要将`YOUR_API_KEY`替换为您的实际API密钥。此示例仅提供了基本的获取当前天气信息的功能,您可以根据具体需求进行扩展和修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值