谷歌推薦用HttpUrlConnectionjava
HttpURLConnection默認使用GET方式 :緩存
URL url = new URL("www.baidu.com"); //使用HttpURLConnection打開鏈接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); //獲得讀取的內容(流) InputStreamReader in = new InputStreamReader(urlConn.getInputStream()); // 爲輸出建立BufferedReader BufferedReader buffer = new BufferedReader(in); String inputLine = null; //使用循環來讀取得到的數據 while (((inputLine = buffer.readLine()) != null)){ //咱們在每一行後面加上一個"\n"來換行 resultData += inputLine + "\n"; } //關閉InputStreamReader in.close(); //關閉http鏈接 urlConn.disconnect();
使用POST方式,則須要setRequestMethod設置 :app
String httpUrl = "http://192.168.1.110:8080/httpget.jsp"; //得到的數據 String resultData = ""; URL url = null; try { //構造一個URL對象 url = new URL(httpUrl); } catch (MalformedURLException e){ Log.e(DEBUG_TAG, "MalformedURLException"); } if (url != null){ try{ // 使用HttpURLConnection打開鏈接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); //由於這個是post請求,設立須要設置爲true urlConn.setDoOutput(true); urlConn.setDoInput(true); // 設置以POST方式 urlConn.setRequestMethod("POST"); // Post 請求不能使用緩存 urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(true); // 配置本次鏈接的Content-type,配置爲application/x-www-form-urlencoded的 urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 鏈接,從postUrl.openConnection()至此的配置必需要在connect以前完成, // 要注意的是connection.getOutputStream會隱含的進行connect。 urlConn.connect(); //DataOutputStream流 DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); //要上傳的參數 String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312"); //將要上傳的內容寫入流中 out.writeBytes(content); //刷新、關閉 out.flush(); out.close(); //返回響應結果 BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getinputstream())) string line = br.readline(); while(line != null){ system.out.printli(line); line = br.readline(); }