Java.net How to run an HTTP request

I am using java.net to send HTTP requests in my Java client, and I still cannot figure out / find how to actually run the request.

For example, I have this code:

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());
}

In this code, if I do not use these lines:

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

the request is never sent. Therefore, in this case, the request seems to trigger by calling InputStream from the connection.

Can someone explain to me how the HTTP request through java.net is launched?

+4
source share
2 answers

From the documentation, it HttpURLConnectionwill connect either if you call connect () , or if you call an operation that depends on how getInputStream().

, URL, . , ( , true), .

URLConnection : , . (, doInput UseCaches). , , . , , getContentLength, , , .

, connect() , getInputStream() (, , , , getResponseCode()), :

Java URLConnection - connect()?

HttpURLConnection HTTP-

PUT, DELETE HTTP- HttpURLConnection?

+5

URLConnection URL URLStreamHandler.openConnection(URL).

, URLConnection . URLConnection.connect(). . javadoc

    String url = "http://example.com";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
0

Source: https://habr.com/ru/post/1666003/


All Articles