Newer
Older
osmCoverage / src / osm / jp / api / HttpPOST.java
package osm.jp.api;

import java.net.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.io.*;

/**
 * Java HTTP クライアントサンプル - HttpURLConnection 版 -
 *
 * @author 68user http://X68000.q-e-d.net/~68user/
 */
public class HttpPOST {
    //public static String host = "http://api06.dev.openstreetmap.org";
    //public static String host = "http://api.openstreetmap.org";
    public static String host = "http://overpass-api.de";

    public static void main(String[] args) throws MalformedURLException, ProtocolException, IOException {
        double minlat = 35.13d;
        double maxlat = 35.66d;
        double minlon = 138.99d;
        double maxlon = 139.79d;
        getCapabilities(new File("output.xml"), "highway", "bus_stop", minlat, maxlat, minlon, maxlon);
        getCapabilities(new File("output.xml"), "highway", "disused:bus_stop", minlat, maxlat, minlon, maxlon);
        getCapabilities(new File("output.xml"), "amenity", "bus_station", minlat, maxlat, minlon, maxlon);
        getCapabilities(new File("output.xml"), "public_transport", "platform", minlat, maxlat, minlon, maxlon);
        getCapabilities(new File("output.xml"), "public_transport", "stop_position", minlat, maxlat, minlon, maxlon);
    }
	
    public static void getCapabilities(File oFile, String key, String value, double minLat, double maxLat, double minLon, double maxLon) throws MalformedURLException, ProtocolException, IOException {
        if (oFile.isFile()) {
            oFile.delete();
        }

        BufferedWriter hw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(oFile), "UTF-8"));
        getCapabilities(hw, key, value, minLat, maxLat, minLon, maxLon);
        hw.close();
    }
	
    public static void getCapabilities(BufferedWriter hw, String key, String value, double minLat, double maxLat, double minLon, double maxLon) throws MalformedURLException, ProtocolException, IOException {
        System.out.println(host + "/api/interpreter");
        URL url = new URL(host + "/api/interpreter");
        int responsecode = 0;

        do {
            HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
            urlconn.setRequestMethod("POST");
            urlconn.setDoOutput(true);              		// POSTのデータを後ろに付ける
            urlconn.setInstanceFollowRedirects(false);		// 勝手にリダイレクトさせない
            urlconn.setRequestProperty("Accept-Language", "ja;q=0.7,en;q=0.3");
            urlconn.setRequestProperty("Content-Type","text/xml;charset=utf-8");
            urlconn.connect();

            // 送信
            PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(urlconn.getOutputStream(), "utf-8")));
            outputWriter(pw, "<osm-script timeout=\"900\" element-limit=\"1073741824\">");
            outputWriter(pw, " <union>");
            outputWriter(pw, "  <query type=\"node\">");
            outputWriter(pw, "   <has-kv k=\""+ key +"\" v=\""+ value +"\"/>");
            outputWriter(pw, "   <bbox-query s=\"" + minLon + "\" n=\"" + maxLon + "\" w=\"" + minLat + "\" e=\"" + maxLat + "\"/>");
            outputWriter(pw, "  </query>");
            outputWriter(pw, " </union>");
            outputWriter(pw, " <print/>");
            outputWriter(pw, "</osm-script>");
            pw.close();       		// closeで送信完了

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {}

            responsecode = urlconn.getResponseCode();
            System.out.println("レスポンスコード[" + responsecode + "] " +
                               "レスポンスメッセージ[" + urlconn.getResponseMessage() + "]");
            Map<String,List<String>> headers = urlconn.getHeaderFields();
            for (Map.Entry<String, List<String>> bar : headers.entrySet()) {
                System.out.print("\t" + bar.getKey() +"\t: ");  // キーを取得
                List<String> vals = bar.getValue();  // 値を取得
                for(String str : vals) {
                    System.out.print("["+ str +"],");
                }
                System.out.println();
            }
            if ((responsecode == 429) || (responsecode == 504) || (responsecode == 500)) {
                // レスポンスコード[429] レスポンスメッセージ[Too Many Requests]
                // レスポンスコード[500] レスポンスメッセージ[Internal server error]
                // レスポンスコード[504] レスポンスメッセージ[Gateway Timeout]
                try {
                    TimeUnit.MINUTES.sleep(5);
                } catch (InterruptedException e) {}
            }
            else {
                System.out.println("\n---- ボディ ----");

                BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), "UTF-8"));
                while (true) {
                    String line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    hw.write(line);
                    hw.newLine();
                }
                reader.close();
            }
            urlconn.disconnect();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {}
        }
        while ((responsecode == 429) || (responsecode == 504));
    }

	
    public static void outputWriter(PrintWriter pw, String text) {
        System.out.println("\t" + text);
        pw.print(text);
    }
}