简体   繁体   中英

Use CONNECT with HttpURLCOnnection

I'm trying to get the data the server sends when i connect to it,

HttpURLConnection con = (HttpURLConnection) new URL("http://myurl.com:443").openConnection();

con.setRequestMethod("CONNECT");

BufferedReader reader;

if(con.getResponseCode() >= 100 && con.getResponseCode() < 400) {
    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
}else {
    reader = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}

String line;
while((line = reader.readLine()) != null) {
    System.out.println(line);
}

but i get the error

Invalid HTTP method: CONNECT

Why can't I use CONNECT as a RequestMethod?

From the doc HttpURLConnection.setRequestMethod :

setRequestMethod

public void setRequestMethod(String method) throws ProtocolException

Set the method for the URL request, one of:
GET
POST
HEAD
OPTIONS
PUT
DELETE
TRACE

are legal, subject to protocol restrictions. The default method is GET.
Parameters:
method - the HTTP method
Throws:
ProtocolException - if the method cannot be reset or if the requested method isn't valid for HTTP.
SecurityException - if a security manager is set and the method is "TRACE", but the "allowHttpTrace" NetPermission is not granted.
See Also:
getRequestMethod()

AS per java doc you can only set GET POST HEAD OPTIONS PUT DELETE TRACE as request method. Connect is not a valid request method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM