gpt4 book ai didi

java - HttpURLConnection 握手和请求发送

转载 作者:行者123 更新时间:2023-12-02 06:08:35 27 4
gpt4 key购买 nike

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

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

Operations that depend on being connected, like getContentLength, will implicitly perform the connection, if necessary.

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

关于java - HttpURLConnection 握手和请求发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22086113/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com