package cn.gis; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /** * 路径分析 * @author 刘仁奎 */ public class GISData { /** * Get请求方式 * * @param urlAddress 请求地址 * @param encodedType 编码方式,UTF-8,GBK... */ public static String getData(String urlAddress, String encodedType) { try { URL url = new URL(urlAddress); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 打开和URL之间的联接 // 获取返回数据,使用 utf-8 将流数据进行转码,否则会产生乱码 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encodedType)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = in.readLine()) != null) { sb.append(line); } in.close(); // 关闭流 return sb.toString(); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * POST 请求方式 * * @param urlAddress 请求地址 * @param encodedType 编码方式,UTF-8,GBK... */ public static String postData(String urlAddress, String encodedType) { try { URL url = new URL(urlAddress); URLConnection conn = url.openConnection(); // 打开联接 // 使用POST请求,是否向connection输出/输入,因为这个是post请求,参数要放在http正文内,因此需要设为true conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // Post请求不用设置缓存 // // 发送域信息 // OutputStreamWriter out = new // OutputStreamWriter(conn.getOutputStream(), "utf-8"); // out.flush(); // out.close(); // 关闭流 // 获取返回数据 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String line = null; StringBuffer sb = new StringBuffer(); while ((line = in.readLine()) != null) { sb.append(line); } in.close(); // 关闭流 return sb.toString(); } catch (Exception e) { e.printStackTrace(); } return ""; } public static void main(String[] args) { String urlAddress = "http://gis.bjxch.gov.cn:5002/NavigationService.do?request=navigating&sx=498802.9959&sy=307318.7775&ex=500844.8565&ey=304921.25269999&flag=0&type=0&coordtype=0"; // 返回的数据,如xml或json等数据 System.out.println("————————GET————————"); System.out.println(getData(urlAddress, "utf-8")); // GET 方式 System.out.println("————————POST————————"); System.out.println(postData(urlAddress, "utf-8")); // POST 方式 } }
时间: 2024-12-27 22:34:10