java.net如何触发HTTP请求

sca*_*ace 4 java httprequest

我使用java.net在我的Java客户端发送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());
}
Run Code Online (Sandbox Code Playgroud)

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

BufferedReader br = new BufferedReader( new InputStreamReader( con.getInputStream() ) );
System.out.println( br.readLine() );
Run Code Online (Sandbox Code Playgroud)

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

任何人都可以解释我如何通过java.net触发HTTP请求?

Arn*_*aud 5

从文档中,HttpURLConnection如果您调用connect(),或者如果您调用依赖于连接的操作,则会连接getInputStream().

如果尚未建立此类连接,则打开此URL引用的资源的通信链接.如果在已经打开连接时调用connect方法(由具有值true的连接字段指示),则忽略该调用.

URLConnection对象经历两个阶段:首先创建它们,然后连接它们.在创建之后,在连接之前,可以指定各种选项(例如,doInput和UseCaches).连接后,尝试设置它们是错误的. 依赖于连接的操作(如getContentLength)在必要时隐式执行连接.

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

Java URLConnection - 我什么时候需要使用connect()方法?

为什么HttpURLConnection不发送HTTP请求

如何在HttpURLConnection中发送PUT,DELETE HTTP请求?