我从互联网上找到了下面的2条代码,并且正在我的应用程序中使用它。

我真的不明白的一件事是,为什么没有调用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();
    }

最佳答案

URLConnection#connect()


  如果需要,依赖于连接的操作(如getContentLength)将隐式执行连接。


这包括getOutputStream()getResponseCode()。因此,当您调用getResponseCode()时,将隐式调用connect()

09-19 19:33