[英]HttpURLConnection handshake and request send
我從互聯網上找到了下面的2段代碼,我在我的應用程序中使用它。
我真的不明白的一件事是,為什么沒有HttpUrlConnection.connect()
來建立Http連接(握手),並且沒有調用任何函數將requst發送到服務器? 誰能解釋一下? 如何跳過代碼但仍然可以獲得響應?
// 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();
}
依賴於連接的操作(如getContentLength)將在必要時隱式執行連接。
這包括getOutputStream()
和getResponseCode()
。 因此,當您調用getResponseCode()
,會隱式調用connect()
。
您不必顯式調用connect
函數,
見java doc
http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#openConnection%28%29
每次調用此URL的協議處理程序的URLStreamHandler.openConnection(URL)方法時,都會創建一個新的URLConnection實例。
應該注意,URLConnection實例在創建時不建立實際的網絡連接。 只有在調用URLConnection.connect()時才會發生這種情況。
如果對於URL的協議(例如HTTP或JAR),存在屬於以下包之一或其子包之一的公共專用URLConnection子類:java.lang,java.io,java.util,java.net,返回的連接將是該子類。 例如,對於HTTP,將返回HttpURLConnection,對於JAR,將返回JarURLConnection。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.