- Class HttpURLConnection
- Field Summary
- Fields declared in class java.net.URLConnection
- Constructor Summary
- Method Summary
- Methods declared in class java.net.URLConnection
- Methods declared in class java.lang.Object
- Field Details
- method
- chunkLength
- fixedContentLength
- fixedContentLengthLong
- responseCode
- responseMessage
- instanceFollowRedirects
- 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
- getHeaderFieldKey
- setFixedLengthStreamingMode
- setFixedLengthStreamingMode
- setChunkedStreamingMode
- getHeaderField
- setFollowRedirects
- getFollowRedirects
- setInstanceFollowRedirects
- getInstanceFollowRedirects
- setRequestMethod
- Java url error code
- Resource not found!
- Обработка исключений
- Exception occurred while processing the request
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.
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 url error code
Файл web.xml позволяет указать, какие страницы html или jsp будут отправляться пользователю при отправке статусных кодов ошибок. Для этого в web.xml применяется элемент .
Внутри этого элемента с помощью элемента указывается статусный код ошибки, который надо обработать. А элемент указывает на путь к странице html или jsp, которая будет отправляться пользователю.
Например, добавим в проект в папку WebContent новый файл 404.html со следующим кодом:
Resource not found!
В файле web.xml определим следующее содержимое:
В данном случае элемент error-code указывает, что мы будем обрабатывать ошибки со статусным кодом 404 (то есть такие ошибки, которые подразумевают отсутствие ресурса на сервере). А элемент location указывает, что в случае обращения к несуществующему ресурсу пользователю будет отправляться страница 404.html.
Обработка исключений
Кроме настройки обработки стандартных ошибок протокола http,типа 404 или 403, файл web.xml позволяет настроить обработку исключений, которые могут возникнуть при обработке запроса. Для этого в web.xml применяется элемент
Например, добавим в проект в папку WebContent новый файл error.jsp и определим в нем следующий код:
Exception occurred while processing the request
Type:
Message:
Данная страница jsp будет отображать информацию об исключении. Через глобальный объект pageContext в страницу передается контекст. Если при обработке запроса возникло какое-нибудь исключение, то метод pageContext.getException() возвратит это исключение в виде объекта Exception. И далее мы можем исследовать этот объект и вызывать его методы, например, получить тип исключения и сообщение об исключении.
Симитируем с сервлете какое-нибудь исключение:
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/hello") public class HelloServlet extends HttpServlet < protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < int x = 0; int y = 8 / x; >>
В данном случае мы получаем ошибку деления на нуль, которая представлена типом java.lang.ArithmeticException.
Теперь определим следующий файл web.xml:
java.lang.Throwable /error.jsp
Элемент exception-type указывает, что обрабатываться будут исключения типа java.lang.Throwable. Поскольку это базовый класс для всех типов исключений, то фактически мы будем обрабатывать все исключения. Хотя можно конкретизировать тип исключения, например, указать тот же java.lang.ArithmeticException.
Элемент location определяет страницу, которая отправляется пользователю при возникновении исключении. В данном случае это error.jsp.
В итоге при обращении к сервлету будет сгенерировано исключение, и мы увидим информацию о нем: