📄 httpgdatarequest.java
字号:
protected HttpURLConnection getRequestConnection(URL requestUrl) throws IOException { if (!requestUrl.getProtocol().startsWith("http")) { throw new UnsupportedOperationException("Unsupported scheme:" + requestUrl.getProtocol()); } HttpURLConnection uc = (HttpURLConnection)requestUrl.openConnection(); // Should never cache GData requests/responses uc.setUseCaches(false); // Always follow redirects uc.setInstanceFollowRedirects(true); return (HttpURLConnection) uc; } /** * Sets the number of milliseconds to wait for a connection to the * remote GData service before timing out. * * @param timeout the read timeout. A value of zero indicates an * infinite timeout. * @throws IllegalArgumentException if the timeout value is negative. * * @see java.net.URLConnection#setConnectTimeout(int) */ public void setConnectTimeout(int timeout) { if (timeout < 0) { throw new IllegalArgumentException("Timeout cannot be negative"); } connectTimeout = timeout; } /** * Sets the number of milliseconds to wait for a response from the * remote GData service before timing out. * * @param timeout the read timeout. A value of zero indicates an * infinite timeout. @throws IllegalArgumentException if the timeout value is negative. * * @see java.net.URLConnection#setReadTimeout(int) */ public void setReadTimeout(int timeout) { if (timeout < 0) { throw new IllegalArgumentException("Timeout cannot be negative"); } readTimeout = timeout; } /** * Sets the If-Modified-Since date precondition to be applied to the * request. If this precondition is set, then the request will be * performed only if the target resource has been modified since the * specified date; otherwise, a {@code NotModifiedException} will be * thrown. */ public void setIfModifiedSince(DateTime conditionDate) { this.ifModifiedCondition = conditionDate; } /** * Returns a stream that can be used to write request data to the * GData service. * * @return OutputStream that can be used to write GData request data. * @throws IOException error obtaining the request output stream. */ public OutputStream getRequestStream() throws IOException { if (!expectsInput) { throw new IllegalStateException("Request doesn't accept input"); } return httpConn.getOutputStream(); } /** * Sets request method (and logs it, if enabled) * * @param method Http method name. * @throws ProtocolException exception. */ public void setMethod(String method) throws ProtocolException { httpConn.setRequestMethod(method); if (logger.isLoggable(Level.FINE)) { logger.fine(method + " " + httpConn.getURL().toExternalForm()); } } /** * Sets request header (and logs it, if enabled) */ public void setHeader(String name, String value) { httpConn.setRequestProperty(name, value); logger.finer(name + ": " + value); } /** * Sets request header and log just it's name, not it's value */ public void setPrivateHeader(String name, String value) { httpConn.setRequestProperty(name, value); logger.finer(name + ": <Not Logged>"); } /** * Executes the GData service request. * * @throws IOException error writing to or reading from GData service. * @throws ServiceException service invocation error. */ public void execute() throws IOException, ServiceException { if (connectTimeout >= 0) { httpConn.setConnectTimeout(connectTimeout); } if (readTimeout >= 0) { httpConn.setReadTimeout(readTimeout); } if (ifModifiedCondition != null) { setHeader("If-Modified-Since", ifModifiedCondition.toStringRfc822()); } // Set the http.strictPostRedirect property to prevent redirected // POST/PUT/DELETE from being mapped to a GET. This // system property was a hack to fix a jdk bug w/out changing back // compat behavior. It's bogus that this is a system (and not a // per-connection) property, so we just change it for the duration // of the connection. // See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4023866 String httpStrictPostRedirect = System.getProperty("http.strictPostRedirect"); try { System.setProperty("http.strictPostRedirect", "true"); httpConn.connect(); if (logger.isLoggable(Level.FINE)) { // Avoid calling URL.equals() unless an object equivalence test fails, // because URL.equals() requires DNS resolution. This test will // fail on the first check for any URLConnection implementation // that derives from java.net.URLConnection. The 2nd check would // work on an alternate impl that clones the URL. if (httpConn.getURL() != requestUrl && !httpConn.getURL().toExternalForm().equals( requestUrl.toExternalForm())) { logger.fine("Redirected to:" + httpConn.getURL().toExternalForm()); } // Log response information here, if enabled logger.fine(httpConn.getResponseCode() + " " + httpConn.getResponseMessage()); if (logger.isLoggable(Level.FINER)) { for (Map.Entry<String,List<String>> headerField: httpConn.getHeaderFields().entrySet()) { for (String value: headerField.getValue()) { logger.finer(headerField.getKey() + ": " + value); } } } } checkResponse(); // will flush any request data } finally { if (httpStrictPostRedirect == null) { System.clearProperty("http.strictPostRedirect"); } else { System.setProperty("http.strictPostRedirect", httpStrictPostRedirect); } } executed = true; } /** * Called after a request is executed to process the response and * generate an appropriate exception (on failure). */ protected void checkResponse() throws IOException, ServiceException { if (httpConn.getResponseCode() >= 300) { handleErrorResponse(); } } /** * Handles an error response received while executing a GData service * request. Throws a {@link ServiceException} or one of its subclasses, * depending on the failure conditions. * @throws ServiceException exception describing the failure. * @throws IOException error reading the error response from the * GData service. */ protected void handleErrorResponse() throws ServiceException, IOException { switch (httpConn.getResponseCode()) { case HttpURLConnection.HTTP_NOT_FOUND: throw new ResourceNotFoundException(httpConn); case HttpURLConnection.HTTP_BAD_REQUEST: throw new InvalidEntryException(httpConn); case HttpURLConnection.HTTP_FORBIDDEN: throw new ServiceForbiddenException(httpConn); case HttpURLConnection.HTTP_UNAUTHORIZED: throw new AuthenticationException(httpConn); case HttpURLConnection.HTTP_NOT_MODIFIED: throw new NotModifiedException(httpConn); case HttpURLConnection.HTTP_NOT_IMPLEMENTED: throw new NotImplementedException(httpConn); case HttpURLConnection.HTTP_CONFLICT: throw new VersionConflictException(httpConn); default: throw new ServiceException(httpConn); } } /** * Returns the content type of the GData response. * <p> * * @return ContentType the GData response content type or {@code null} * if no response content. * @throws IllegalStateException attempt to read content type without * first calling {@link #execute()}. * @throws IOException error obtaining the response content type. */ public ContentType getResponseContentType() throws IOException { if (!executed) { throw new IllegalStateException( "Must call execute() before attempting to read response"); } String value = httpConn.getHeaderField("Content-Type"); if (value == null) { return null; } return new ContentType(value); } /** * Returns a stream that can be used to read response data from the * GData service. * * @return InputStream providing access to GData response data. * @throws IllegalStateException if attemping to read response without * first calling {@link #execute()}. * @throws IOException error obtaining the response input stream. */ public InputStream getResponseStream() throws IOException { if (!executed) { throw new IllegalStateException( "Must call execute() before attempting to read response"); } if (!hasOutput) { throw new IllegalStateException("Request doesn't have response data"); } InputStream responseStream = httpConn.getInputStream(); if ("gzip".equalsIgnoreCase(httpConn.getContentEncoding())) { responseStream = new GZIPInputStream(responseStream); } return responseStream; } /** * Returns the URLConnection instance that represents the underlying * connection to the GData service that will be used by this request. * * @return connection to GData service. */ public HttpURLConnection getConnection() { return httpConn; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -