HttpURL串連遠程serverGet和Post方式請求並返回資料

來源:互聯網
上載者:User

標籤:www   end   .com   false   string   ring   arc   stat   ret   

查看原文: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本文內,因此須要設為trueconn.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方式請求並返回資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.