簡単なJSPで Watson Weather Company Data から天気予報を取得する



<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.util.Base64"%>
<%@page import="java.net.URLConnection"%>
<%@page import="java.net.URL"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<script>

<%
String json = "{}";
try {

                String username = "xxx";
                String password = "xxx";
                URL url = new URL(
                        "https://twcservice.mybluemix.net/api/weather/v1/geocode/35.681167/139.76705/forecast/daily/3day.json?language=ja-JP");
                URLConnection conn = url.openConnection();
                conn.setRequestProperty(
                        "Authorization",
                        "Basic "
                                + Base64.getEncoder().encodeToString(
                                        (username + ":" + password).getBytes()));
                InputStream is = conn.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        is, "UTF-8"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

                System.out.println(sb.toString());
                json = sb.toString();

                br.close();
            } catch (Throwable th) {
            }
%>

var json = <%=json%>;

</script>


</head>



<body>

<script>
for(var i=0;i<json.forecasts.length;i++){
document.write(json.forecasts[i].narrative);
document.write("<br>");
}
</script>

</body>
</html>