使用HttpURLConnection發送HTTP請求
-
獲取
HttpURLConnection
對象。一般只需new出一個URL對象,并傳入目標的網絡地址,然后調用openConnec()
方法URL url = new URL("http://www.baidu.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
-
設置HTTP請求所使用的方法(
GET
和POST
)- GET 方式是表示從服務器那里獲取數據
- POST 方式是表示希望提交數據給服務器
connection.setRequestMethod("POST");
-
私人訂制連接(設置連接超時、讀取超時的毫秒數以及服務器希望得到的一些消息頭等)
//設置讀取超時 connection.setReadTimeout(5000); //設置連接超時 connection.setConnectTimeout(5000);
-
調用
getInputStream()
方法獲取到服務器返回的輸入流InputStream inputStream = connection.getInputStream();
-
調用
disconnect()
方法將HTTP連接關閉掉connection.disconnect();
提交數據
GET方式
-
get方式提交的數據是直接拼接在url的末尾(鍵值對方式)
final String path = "http://192.168.1.104/Web/servlet/CheckLogin?name=" + name + "&pass=" + pass;
-
發送get請求
URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); if(conn.getResponseCode() == 200){ InputStream inputStream = connection.getInputStream(); }
-
瀏覽器在發送請求攜帶數據時會對數據進行URL編碼,我們寫代碼時也需要為中文進行URL編碼
String path = "http://192.168.1.104/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
POST
post提交數據是用流寫給服務器的
-
協議頭中多了兩個屬性
- Content-Type: application/x-www-form-urlencoded,描述提交的數據的mimetype
- Content-Length: 32,描述提交的數據的長度
/*給請求頭添加post多出來的兩個屬性*/ //進行URL編碼 String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass; //手動設置兩個屬性 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", data.length() + "");
-
設置允許打開post請求的流
conn.setDoOutput(true);
-
獲取連接對象的輸出流,往流里寫要提交給服務器的數據
OutputStream os = conn.getOutputStream(); os.write(data.getBytes());