⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpgdatarequest.java

📁 google gdata API 很好用的API
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    if (headerMap != null) {      for (String h : headerMap.keySet()) {        setHeader(h, headerMap.get(h));      }    }    if (privateHeaderMap != null) {      for (String h : privateHeaderMap.keySet()) {        setPrivateHeader(h, privateHeaderMap.get(h));      }    }    httpConn.setDoOutput(expectsInput);  }  /**   * Obtains a connection to the GData service.   */  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)   */  private 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)   */  private 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)) {        if (!httpConn.getURL().equals(requestUrl)) {          logger.fine("Redirected to:" + httpConn.getURL().toExternalForm());        }        // Log response information here, if enabled        logger.fine(httpConn.getResponseCode() + " " +                    httpConn.getResponseMessage());        if (logger.isLoggable(Level.FINER)) {          Map<String,List<String>> responseHeaders = httpConn.getHeaderFields();          for (String name: responseHeaders.keySet()) {            for (String value: responseHeaders.get(name)) {              logger.finer(name + ": " + 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 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");    }    return httpConn.getInputStream();  }  /**   * 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 + -