繁体   English   中英

HttpURLConnection握手和请求发送

[英]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();
    }

URLConnection#connect()

依赖于连接的操作(如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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM