我發現從互聯網下面的2段代碼,我在我的應用程序中使用它。HttpURLConnection握手和請求發送
我真的不明白的一件事是,爲什麼沒有HttpUrlConnection.connect()
被調用來建立Http連接(握手),並且沒有任何函數被調用來將請求發送到服務器?誰能解釋一下?代碼如何跳過,但仍然可以獲得響應?
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://www.google.com/search?q=mkyong";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
========================================
URL obj = new URL("http://mkyong.com");
URLConnection conn = obj.openConnection();
Map<String, List<String>> map = conn.getHeaderFields();
System.out.println("Printing Response Header...\n");
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " ,Value : " + entry.getValue());
}
System.out.println("\nGet Response Header By Key ...\n");
String server = conn.getHeaderField("Server");
if (server == null) {
System.out.println("Key 'Server' is not found!");
} else {
System.out.println("Server - " + server);
}
System.out.println("\n Done");
} catch (Exception e) {
e.printStackTrace();
}
嘿它的HTTP GET請求。代碼在這裏獲取這行代碼中的url內容:'BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()));' – Peshal