Http connection exception java

Class HttpURLConnection

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.

The HTTP protocol handler has a few settings that can be accessed through System Properties. This covers Proxy settings as well as various other settings.

  • a «connect» SocketPermission to the host/port combination of the destination URL or
  • a URLPermission that permits this request.

If automatic redirection is enabled, and this request is redirected to another destination, then the caller must also have permission to connect to the redirected host/URL.

Field Summary

Fields declared in class java.net.URLConnection

Constructor Summary

Method Summary

Returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

Читайте также:  What is cookies and session in java

Supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection .

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance.

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions.

Methods declared in class java.net.URLConnection

Methods declared in class java.lang.Object

Field Details

method

chunkLength

The chunk-length when using chunked encoding streaming mode for output. A value of -1 means chunked encoding is disabled for output.

fixedContentLength

The fixed content-length when using fixed-length streaming mode. A value of -1 means fixed-length streaming mode is disabled for output. NOTE: fixedContentLengthLong is recommended instead of this field, as it allows larger content lengths to be set.

fixedContentLengthLong

The fixed content-length when using fixed-length streaming mode. A value of -1 means fixed-length streaming mode is disabled for output.

responseCode

  • 1xx: Informational
  • 2xx: Success
  • 3xx: Redirection
  • 4xx: Client Error
  • 5xx: Server Error

responseMessage

instanceFollowRedirects

If true , the protocol will automatically follow redirects. If false , the protocol will not automatically follow redirects. This field is set by the setInstanceFollowRedirects method. Its value is returned by the getInstanceFollowRedirects method. Its default value is based on the value of the static followRedirects at HttpURLConnection construction time.

HTTP_OK

HTTP_CREATED

HTTP_ACCEPTED

HTTP_NOT_AUTHORITATIVE

HTTP_NO_CONTENT

HTTP_RESET

HTTP_PARTIAL

HTTP_MULT_CHOICE

HTTP_MOVED_PERM

HTTP_MOVED_TEMP

HTTP_SEE_OTHER

HTTP_NOT_MODIFIED

HTTP_USE_PROXY

HTTP_BAD_REQUEST

HTTP_UNAUTHORIZED

HTTP_PAYMENT_REQUIRED

HTTP_FORBIDDEN

HTTP_NOT_FOUND

HTTP_BAD_METHOD

HTTP_NOT_ACCEPTABLE

HTTP_PROXY_AUTH

HTTP_CLIENT_TIMEOUT

HTTP_CONFLICT

HTTP_GONE

HTTP_LENGTH_REQUIRED

HTTP_PRECON_FAILED

HTTP_ENTITY_TOO_LARGE

HTTP_REQ_TOO_LONG

HTTP_UNSUPPORTED_TYPE

HTTP_SERVER_ERROR

HTTP_INTERNAL_ERROR

HTTP_NOT_IMPLEMENTED

HTTP_BAD_GATEWAY

HTTP_UNAVAILABLE

HTTP_GATEWAY_TIMEOUT

HTTP_VERSION

Constructor Details

HttpURLConnection

Method Details

setAuthenticator

Supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection . If no authenticator is supplied, the default authenticator will be used.

getHeaderFieldKey

Returns the key for the n th header field. Some implementations may treat the 0 th header field as special, i.e. as the status line returned by the HTTP server. In this case, getHeaderField(0) returns the status line, but getHeaderFieldKey(0) returns null.

setFixedLengthStreamingMode

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance. An exception will be thrown if the application attempts to write more data than the indicated content-length, or if the application closes the OutputStream before writing the indicated amount. When output streaming is enabled, authentication and redirection cannot be handled automatically. A HttpRetryException will be thrown when reading the response if authentication or redirection are required. This exception can be queried for the details of the error. This method must be called before the URLConnection is connected. NOTE: setFixedLengthStreamingMode(long) is recommended instead of this method as it allows larger content lengths to be set.

setFixedLengthStreamingMode

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance. An exception will be thrown if the application attempts to write more data than the indicated content-length, or if the application closes the OutputStream before writing the indicated amount. When output streaming is enabled, authentication and redirection cannot be handled automatically. A HttpRetryException will be thrown when reading the response if authentication or redirection are required. This exception can be queried for the details of the error. This method must be called before the URLConnection is connected. The content length set by invoking this method takes precedence over any value set by setFixedLengthStreamingMode(int) .

setChunkedStreamingMode

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. In this mode, chunked transfer encoding is used to send the request body. Note, not all HTTP servers support this mode. When output streaming is enabled, authentication and redirection cannot be handled automatically. A HttpRetryException will be thrown when reading the response if authentication or redirection are required. This exception can be queried for the details of the error. This method must be called before the URLConnection is connected.

getHeaderField

Returns the value for the n th header field. Some implementations may treat the 0 th header field as special, i.e. as the status line returned by the HTTP server. This method can be used in conjunction with the getHeaderFieldKey method to iterate through all the headers in the message.

setFollowRedirects

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class. True by default. Applets cannot change this variable. If there is a security manager, this method first calls the security manager’s checkSetFactory method to ensure the operation is allowed. This could result in a SecurityException.

getFollowRedirects

setInstanceFollowRedirects

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance. The default value comes from followRedirects, which defaults to true.

getInstanceFollowRedirects

setRequestMethod

Источник

Ошибка java.net.ConnectException: Connection refused – как исправить?

Ошибка java.net.ConnectException: Connection refused является одним из самых распространенных сетевых исключений в Java. Эта ошибка возникает, когда вы работаете с архитектурой клиент-сервер и пытаетесь установить TCP-соединение от клиента к серверу.

Соединение также происходит в случае RMI (удаленного вызова метода), потому что RMI также использует протокол TCP-IP. При написании кода клиентского сокета на Java вы всегда должны обеспечивать правильную обработку этого исключения.

В этом руководстве по Java вы узнаете, почему возникает исключение при отказе в соединении и как решить проблему.

Причины

ошибка java.net.ConnectException: Connection refused

Отказ в соединении – это явный случай, когда клиент пытается подключиться через порт TCP, но не может это сделать. Вот некоторые из возможных причин, почему это происходит:

Да, возможно, что они не подключены к локальной сети, Интернету или любой другой сети.

Вторая наиболее распространенная причина – сервер не работает. Вы можете использовать следующие сетевые команды, например, ping, чтобы проверить, работает ли сервер.

Это еще одна распространенная причина возникновения «java.net.ConnectException: соединение отклонено», когда сервер работает, но видит другой порт. Трудно разобраться в этом случае, пока вы не проверите конфигурацию.

Почти каждая корпоративная сеть защищена. Если вы подключаетесь к сети других компаний, вам нужно убедиться, что они разрешают друг другу IP-адрес и номер порта.

Проверьте последнюю конфигурацию на стороне клиента и сервера, чтобы избежать исключения отказа в соединении.

TCP является базовым протоколом для многих высокоуровневых протоколов, включая HTTP, RMI и другие. Нужно убедиться, что вы передаете правильный протокол, какой сервер ожидает.

Если вам интересно узнать больше об этом, то изучите книгу по сетевым технологиям, такую ​​как Java Network Programming (4-е дополнение), написанную Гарольдом Эллиоттом Расти.

Java Network Programming

Как решить java.net.ConnectException: соединение отказано

Простое решение состоит в том, чтобы сначала выяснить фактическую причину исключения. Здесь важнее всего подход к поиску правильной причины и решения. Как только вы узнаете реальную причину, вам, возможно, даже не потребуется вносить какие-либо существенные изменения.

Вот несколько советов, которые могут помочь исправить ошибку java.net.ConnectException: Connection refused:

  1. Сначала попытайтесь пропинговать целевой хост, если хост способен пинговать, это означает, что клиент и сервер находятся в сети.
  2. Попробуйте подключиться к хосту и порту сервера, используя telnet. Если вы можете подключиться, значит что-то не так с вашим клиентским кодом. Кроме того, наблюдая за выводом telnet, вы узнаете, работает ли сервер или нет, или сервер отключает соединение.

Средняя оценка 1.5 / 5. Количество голосов: 33

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

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