Establishing the URLConnection to another web application does not work with URLConnection .connect()?

对着背影说爱祢 提交于 2020-01-06 20:06:23

问题


Here is the code i am using the open the URLConnection to another webapllication

try {   
 URL   url = new URL("https://mySecondWebApp/Cart");
 HttpsURLConnection conn1 = (HttpsURLConnection) url.openConnection();//line1
 conn1 .connect();//line 2 does not establishes the connection
 conn1.getInputStream();// line 3 works which means that i get control to my app2 in debugger.But this also passes the control to IOException stating error java.io.FileNotFoundException: https://mySecondWebApp/Cart

 }
  catch (MalformedURLException e) {
    log.error("MalformedURLException" + e);

  }
  catch (IOException e) {

  log.info("getting IO error");
  }

I am not getting why line 2 does not establish the connection with app2 while line 3 does? second thing is why i get the file notfound exception after line 3 even though it sucessfully connect to app2 which i want to avoid.My intention is just to establish the connection to app2 so that i get control inside my java code of app2


回答1:


The method name is probably the source of your confusion. openConnection() method does not establish a connection, it just prepares the connection object. here is the link to the API for the method:

URL.openConnection()

the following is written there: "It should be noted that a URLConnection instance does not establish the actual network connection on creation. This will happen only when calling URLConnection.connect()."

EDIT: I have confused the lines (Thanks Ankit) and therefore the above is not relevant. Connecet does establish the connection but actually it is not needed here as the method getInputStream will establish the connection if it was not established already.




回答2:


The connect() method is not expected to do this task, from javadoc:

public abstract void connect()
                      throws IOException

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.



来源:https://stackoverflow.com/questions/11663351/establishing-the-urlconnection-to-another-web-application-does-not-work-with-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!