戻り天気データはapiでHttpURLConnectionを使用して取得します.
1968 ワード
以下はコアコード
//
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を用いて返却データを取得する.