gpt4 book ai didi

Java-HttpUrlConnection

转载 作者:太空宇宙 更新时间:2023-11-04 06:43:55 25 4
gpt4 key购买 nike

您好,我已经开始使用 HttpUrlConnection,我有一个关于 Http 请求实际发送时间的问题。

我在某处读到,调用 getInputStream() 时会发送实际请求。不过,我已经编写了一些测试代码来处理 POST 请求:

在此版本中,我在 getInputStream() 之前调用 getResponseCode()

URL obj = new URL(myUrl);
HttpURLConnection httpclient = (HttpURLConnection) obj.openConnection();
httpclient.setRequestMethod("POST");
**int responseCode = httpclient.getResponseCode();**
try {
inStream = httpclient.getInputStream();
}
catch (IOException ie) {
inStream = httpclient.getErrorStream();
}
System.out.println("response code = " + responseCode);

我收到响应代码 200。所以这让我想到请求不是在 getInputStream() 处发送的,而是在较早的方法处发送的。有人对此有任何见解吗?

谢谢!

最佳答案

HttpURLConnection#getResponseCode() 的代码洞察 - openJDK 7

public int getResponseCode() throws IOException {
454 /*
455 * We're got the response code already
456 */
457 if (responseCode != -1) {
458 return responseCode;
459 }
460
461 /*
462 * Ensure that we have connected to the server. Record
463 * exception as we need to re-throw it if there isn't
464 * a status line.
465 */
466 Exception exc = null;
467 try {
468 getInputStream();
469 } catch (Exception e) {
470 exc = e;
471 }
472 ...

基本上,响应代码在初始化时将为-1,这意味着我们没有收到任何响应代码。因此它将建立一个连接URL#getInputStream()并获取响应代码。

关于Java-HttpUrlConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24300400/

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