我在我的 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?
关于java.net 如何触发 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41507930/