HttpURL連接遠程serverGet和Post方式請求並返回數據
阿新 • • 發佈:2017-07-03
spa tostring exc fcm target public writer 連接 article
查看原文:http://www.ibloger.net/article/1813.html
package cn.gis; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /** * 路徑分析 */ 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://server.arcgisonline.com/arcgis/services?wsdl"; // 返回的數據,如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 方式 } }
HttpURL連接遠程serverGet和Post方式請求並返回數據