Java httpurlconnection with https

Class HttpsURLConnection

See http://www.w3.org/pub/WWW/Protocols/ and RFC 2818 for more details on the https specification.

This class uses HostnameVerifier and SSLSocketFactory . There are default implementations defined for both classes. However, the implementations can be replaced on a per-class (static) or per-instance basis. All new HttpsURLConnection s instances will be assigned the «default» static values at instance creation, but they can be overridden by calling the appropriate per-instance set method(s) before connect ing.

Field Summary

Fields declared in class java.net.HttpURLConnection

Fields declared in class java.net.URLConnection

Constructor Summary

Method Summary

Sets the SSLSocketFactory to be used when this instance creates sockets for secure https URL connections.

Methods declared in class java.net.HttpURLConnection

Methods declared in class java.net.URLConnection

Methods declared in class java.lang.Object

Field Details

hostnameVerifier

Constructor Details

HttpsURLConnection

Method Details

getCipherSuite

getLocalCertificates

Returns the certificate(s) that were sent to the server during handshaking. Note: This method is useful only when using certificate-based cipher suites. When multiple certificates are available for use in a handshake, the implementation chooses what it considers the «best» certificate chain available, and transmits that to the other side. This method allows the caller to know which certificate chain was actually sent.

getServerCertificates

Returns the server’s certificate chain which was established as part of defining the session. Note: This method can be used only when using certificate-based cipher suites; using it with non-certificate-based cipher suites, such as Kerberos, will throw an SSLPeerUnverifiedException. Note: The returned value may not be a valid certificate chain and should not be relied on for trust decisions.

Читайте также:  Java text color swing

getPeerPrincipal

Returns the server’s principal which was established as part of defining the session. Note: Subclasses should override this method. If not overridden, it will default to returning the X500Principal of the server’s end-entity certificate for certificate-based ciphersuites, or throw an SSLPeerUnverifiedException for non-certificate based ciphersuites, such as Kerberos.

getLocalPrincipal

Returns the principal that was sent to the server during handshaking. Note: Subclasses should override this method. If not overridden, it will default to returning the X500Principal of the end-entity certificate that was sent to the server for certificate-based ciphersuites or, return null for non-certificate based ciphersuites, such as Kerberos.

setDefaultHostnameVerifier

Sets the default HostnameVerifier inherited by a new instance of this class. If this method is not called, the default HostnameVerifier assumes the connection should not be permitted.

getDefaultHostnameVerifier

setHostnameVerifier

Sets the HostnameVerifier for this instance. New instances of this class inherit the default static hostname verifier set by setDefaultHostnameVerifier . Calls to this method replace this object’s HostnameVerifier .

getHostnameVerifier

setDefaultSSLSocketFactory

Sets the default SSLSocketFactory inherited by new instances of this class. The socket factories are used when creating sockets for secure https URL connections.

getDefaultSSLSocketFactory

Gets the default static SSLSocketFactory that is inherited by new instances of this class. The socket factories are used when creating sockets for secure https URL connections.

setSSLSocketFactory

Sets the SSLSocketFactory to be used when this instance creates sockets for secure https URL connections. New instances of this class inherit the default static SSLSocketFactory set by setDefaultSSLSocketFactory . Calls to this method replace this object’s SSLSocketFactory .

getSSLSocketFactory

getSSLSession

Returns an Optional containing the SSLSession in use on this connection. Returns an empty Optional if the underlying implementation does not support this method.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Читайте также:  Javascript addeventlistener click event

Источник

Особенности HttpUrlConnection из java.net

сегодня постараюсь рассказать о том, как можно отправить запрос и прочитать ответ от HTTP сервера, используя URLConnection из библиотеки JRE.

  • users.list
  • chat.postMessage
  • conversations.create
  • files.upload
  • im.open
GET /users.list HTTP/1.1 Content-Type: application/x-www-form-urlencoded token=xoxp-1234567890-098765-4321-a1b2c3d4e5 

Я знал про библиотеку Apache HttpComponents, но для иследовательских целей будем использовать средства доступные в стандартной библиотеке Java 8, а именно имплементацию java.net.URLConnection.

Для получений сущности URLConnection нужно использовать объект класса java.net.URL, его конструктор принимает тип String где помимо всего должен быть указан протокол – в нашем случае https.

После получения сущности URL, вызываем метод openConnection() который возвратит нам сущность HttpsUrlConnection.

String url = “https://slack.com/api/users.list”; URLConnection connection = new URL(url).openConnection(); 

При этом нужно обработать или пробросить MalformedUrlException и IOException.

После этого переменная connection будет хранить ссылку на объект HttpsUrlConnectionImpl. По умолчанию будет формироваться GET-запрос, для того чтобы добавить Header используем метод setRequestProperty(), который принимает key и value. Нам здесь нужно установить Content-Type который имеет значение application/x-www-form-urlencoded. Ну, и мы это делаем!

connection.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”); 

Теперь осталось только отправить запрос записав в тело наш токен и лимит. Для этого нужно установить поле doOutput объекта connection в положение true, используя метод setDoOutput();

connection.setDoOutput(true); 

Далее самая интересная часть — нужно как-то передать наше тело запроса в OutputStream. Будем использовать OutputStreamWriter:

OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); 

Есть один нюанс: после того, как мы вызвали метод getOutputStream() метод запроса меняется на POST, так как GET не предусматривает наличие request body, но благо что slack ни ставит твёрдое ограничение на метод поэтому всё было хорошо. И поэтому GET-запрос должен выглядеть так:

GET /users.list?token=xoxp-1234567890-098765-4321-a1b2c3d4e5&limit=100 HTTP/1.1 Content-Type: application/x-www-form-urlencoded 

Но я не стал уже переделывать. И вместо этого наш запрос получился таким:

POST /users.list HTTP/1.1 Content-Type: application/x-www-form-urlencoded token=xoxp-1234567890-098765-4321-a1b2c3d4e5 

(*некоторые headers ставятся самим HttpsUrlConnection и здесь они отсутствуют)

Читайте также:  What is annotation in java spring

И так чтоб записать наше тело запроса пользуемся write();.

String reqBody = “token=xoxp-1234567890-098765-4321-a1b2c3d4e5&limit=100”; writer.write(reqBody); writer.close(); 

После этого наш запрос будет отправлен, и мы можем прочитать полученный ответ. Важно закрывать OutputStream или делать flush(), перед тем как получать InputStream, иначе данные не уйдут из буффера(как альтернатива можно использовать PrintStream — в методе println() по умолчанию вызывается flush()). Для чтение использовал BufferedReader:

StringBuilder respBody = new StringBuilder(); BufferedReader reader = new BufferedReader(connection.getInputStream()); reader.lines().forEach(l -> respBody.append(l + “\r\n”); reader.close(); 

(*используем lines() чтобы получить Stream на выходе; \r\n – символ CRLF – вставляет переход на новую строку)

И, если мы успешно проходим аутентификацию, переменная respBody должна хранить наш ответ от сервера, что в нашем случае является JSON объектом. После этого, его можно отправлять на следующий этап обработки.

После некоторой оптимизации всё выглядет так:

package main.java.com.bilichenko.learning; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.Optional; import java.util.stream.Collectors; public class SlackClient < private static final String HOST = "https://api.slack.com"; private static final String GET_USERS_URI = "/api/users.list"; private static final String TOKEN = "xx-ooo-YOUR-TOKEN-HERE"; public static void main(String[] args) throws IOException < SlackClient slackClient = new SlackClient(); System.out.println(slackClient.getRawResponse(HOST + GET_USERS_URI, "application/x-www-form-urlencoded", "token=" + TOKEN).orElse("no response")); >public Optional getRawResponse(String url, String contentType, String requestBody) throws MalformedURLException, IOException < HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestProperty("Content-Type", contentType); connection.setConnectTimeout(10000); connection.setRequestMethod("POST"); connection.setDoOutput(true); try(OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream())) < writer.write(requestBody); >if (connection.getResponseCode() != 200) < System.err.println("connection failed"); return Optional.empty(); >try(BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream(), Charset.forName("utf-8")))) < return Optional.of(reader.lines().collect(Collectors.joining(System.lineSeparator()))); >> > 

Источник

Оцените статью