通过api使用HttpURLConnection 获取返回天气数据。



以下是核心代码

//严苛模式
if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

HttpURLConnection conn = null;
BufferedReader reader = null;
//使用免费api查询天气,请求数据时需要提交的参数
Map params = new HashMap();
StringBuilder stringBuilder = new StringBuilder();

params.put("cityname", "武汉");
params.put("key", "25e29678acc94631ebfc5c329d887162");
params.put("dtype", "json");
//将map型转为请求参数型
for (Map.Entry i : params.entrySet()) {
    try {
        stringBuilder.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
//组装成带参数的请求地址
String requestURL = "http://op.juhe.cn/onebox/weather/query" + "?" + stringBuilder.toString();
try {
    //存储返回结果
    String result = null;
    String strRead = null;
    //开始连接
    URL url = new URL(requestURL);
    conn = (HttpURLConnection) url.openConnection();
    //使用Get方式请求数据
    conn.setRequestMethod("GET");
    conn.connect();
    //输入流获取返回数据
    InputStream is = conn.getInputStream();
    reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    while ((strRead = reader.readLine()) != null) {
        stringBuilder.append(strRead);
    }
    result = stringBuilder.toString();
    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (conn != null) {
        conn.disconnect();
    }
}
严苛模式是一个开发工具,能够检测程序中的违例,从而修复。这里通过api使用HttpURLConnection 获取返回数据。

你可能感兴趣的:(通过api使用HttpURLConnection 获取返回天气数据。)