What is the purpose of setDoInput and setDoOutput in Java HttpURLConnection?

后端 未结 3 1043
不知归路
不知归路 2020-12-29 18:55

What is the function or purpose of HttpURLConnection.setDoInput and HttpURLConnection.setDoOutput?

相关标签:
3条回答
  • 2020-12-29 19:15

    I was still confused as to what exactly was meant in the documentation by "Use the url connection for input".

    That could mean that you want read information from the response or that you want to input information into its request. The documentation states:

    A URL connection can be used for input and/or output. Setting the doInput flag to true indicates that the application intends to read data from the URL connection.

    The default value of this field is true.

    So if you want to ignore data from the response then you can set doInput to false. If you want to use getInputStream() then you should leave this alone or set it to true.

    A URL connection can be used for input and/or output. Setting the doOutput flag to true indicates that the application intends to write data to the URL connection.

    The default value of this field is false.

    So if you want append data to the request (calling getOutputStream()) then you must set doOutput to true.

    0 讨论(0)
  • 2020-12-29 19:27

    The methods are declared by the superclass, URLConnection. I think the intention was to enable potential optimizations in the concrete implementations. Remember that URLConnection is protocol agnostic (but HttpURLConnection is obviously not).

    0 讨论(0)
  • 2020-12-29 19:36

    From the documentation for URLConnection:

    Set the DoInput flag to true if you intend to use the URL connection for input, false if not. The default is true.

    Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. The default is false.

    As for the actual purpose, it doesn't appear that anything in the Oracle code checks on the doInput variable. However the doOutput default of false will prevent you from calling getOutputStream() necessary for HTTP POST requests. So it is a way to indicate ahead of time that you expect to write to an OutputStream without actually establishing it.

    0 讨论(0)
提交回复
热议问题