java.net 如何触发 HTTP 请求

标签 java httprequest

我在我的 Java 客户端中使用 java.net 发送 HTTP 请求,但我仍然无法意识到/找到如何实际触发请求。

例如我有这段代码:

Scanner sc = new Scanner(System.in);

System.out.println("Deleting subject...");
System.out.println("Subject shortcut (-1 for return):");
String shortcut = sc.next();
if( shortcut.equals("-1") )
    return ;

try
{
    URL url = new URL( "http://localhost:8080/Server/webresources/subject/delete/"+shortcut );
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("DELETE");

    BufferedReader br = new BufferedReader( new InputStreamReader( con.getInputStream() ) );
    System.out.println( br.readLine() );
}catch( Exception e )
{
    System.out.println(e.getMessage());
}

在这段代码中,如果我不使用这些行:

BufferedReader br = new BufferedReader( new InputStreamReader( con.getInputStream() ) );
System.out.println( br.readLine() );

请求永远不会发送。所以在这种情况下,请求似乎是通过从连接调用 InputStream 来触发的。

谁能解释一下如何通过 java.net 触发 HTTP 请求?

最佳答案

根据文档,如果您调用 connect()HttpURLConnection 将连接,或者如果您调用依赖于连接的操作,例如 getInputStream()

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established. If the connect method is called when the connection has already been opened (indicated by the connected field having the value true), the call is ignored.

URLConnection objects go through two phases: first they are created, then they are connected. After being created, and before being connected, various options can be specified (e.g., doInput and UseCaches). After connecting, it is an error to try to set them. Operations that depend on being connected, like getContentLength, will implicitly perform the connection, if necessary.

但是,有几个主题表明 connect() 不会提交实际请求,但是 getInputStream()(很可能是任何读取服务器响应的方法,例如 getResponseCode() ),将:

Java URLConnection - When do I need to use the connect() method?

Why does HttpURLConnection not send the HTTP request

How to send PUT, DELETE HTTP request in HttpURLConnection?

关于java.net 如何触发 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41507930/

相关文章:

java - 未触发 Firebase 异步上传到 Cloud Firestore

javascript - 在 Dart 中创建 POST HttpRequest (XMLHttpRequest)

arrays - JSON 语法 - 正文发布请求 - SWIFT4

c# - 如何将 int 数组作为主体参数传递到 HTTP 触发的、点网隔离的 V4 Azure 函数中?

java - 运行 Java Web 应用程序时出现 SQLException

java - 向每个方法引入新变量的通用方法

java - 安卓开机动画

java - Spring 4 Hibernate 4 找不到当前线程的 session

java - Spring,如何通过 header 管理HTTP请求?

asp.net-mvc - ASP.NET MVC - ActionFilterAttribute 用于验证 POST 数据