Javaでwebapiからテキスト取得
自前のサーバだと、sslのエラーが出て取れないけれど、
paizaだとエラーが出ずに実行できる。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.net.*; import java.util.*; import java.io.*; class Main { public static void main(String[] args) { String param = "us/newyork/newyork"; String retJson = pn_c9759a75_herokuapp_com(param); p(retJson); } public static void p(String a){ System.out.println(a); } public static String pn_c9759a75_herokuapp_com(String param) { String retJson = "empty"; URL url; try { String url_s = "https://pn-c9759a75.herokuapp.com/" + param; url = new URL(url_s); URLConnection conn; conn = url.openConnection(); InputStream in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; if ((line = br.readLine()) != null) { // System.out.println(line); retJson = line; } br.close(); } catch (Exception e) { e.printStackTrace(); } return retJson; } } |
1 |
{"address":"us/newyork/newyork","routes":{"japan":"japan/tokyo/shinagawa","uk":"uk/england/london","us/newyork/rochester":"us/newyork/rochester","us/newyork/buffalo":"us/newyork/buffalo","us/california":"us/california/losangeles","default":"us/california/losangeles"}} |