Java Code Examples for org.apache.commons.httpclient.HttpStatus#SC_MOVED_PERMANENTLY

The following examples show how to use org.apache.commons.httpclient.HttpStatus#SC_MOVED_PERMANENTLY . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractHttpClient.java    From alfresco-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean isRedirect(HttpMethod method)
{
    switch (method.getStatusCode()) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_SEE_OTHER:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        if (method.getFollowRedirects()) {
            return true;
        } else {
            return false;
        }
    default:
        return false;
    }
}
 
Example 2
Source File: Filter5HttpProxy.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 请求转向不同同服务器的其他应用
 * </p>
 * @param appServer
 * @param req
 * @param response
 * @throws IOException
 * @throws BusinessServletException
 */
private void proxy4ForeignApplication(AppServer appServer, HttpServletResponse response) throws IOException, BusinessServletException {
       HttpClient client = HttpClientUtil.getHttpClient(appServer); // 创建HttpClient对象
	HttpState httpState = client.getState();
	
	/* 设置用户令牌相关Cookie,包括一个token Cookie和一个 sessionId Cookie */
       boolean isSecure = Context.getRequestContext().isSecure(); //是否https请求
       String currentAppCode = Context.getApplicationContext().getCurrentAppCode(); //当前应用code
       String domain = appServer.getDomain();
       String path   = appServer.getPath(); 
       if (Context.isOnline()) {
           httpState.addCookie(new Cookie(domain, RequestContext.USER_TOKEN, Context.getToken(), path, null, isSecure)); //token = ****************
       }
       if (Environment.getSessionId() != null) {
           httpState.addCookie(new Cookie(domain, currentAppCode, Environment.getSessionId(), path, null, isSecure)); // TSS = JSessionId
       }
	
	HttpMethod httpMethod = HttpClientUtil.getHttpMethod(appServer); // 创建HttpPost对象(等价于一个Post Http Request)
	try {
		// 请求
           int statusCode = client.executeMethod(httpMethod);
		if (statusCode == HttpStatus.SC_OK) {
			// 转发返回信息
			transmitResponse(appServer, response, client, httpMethod);
		} 
		else if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
				|| (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statusCode == HttpStatus.SC_SEE_OTHER)
				|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
		    
			dealWithRedirect(appServer, response, client, httpMethod);
		} 
		
	} finally {
		httpMethod.releaseConnection();
	}
}
 
Example 3
Source File: AbstractSolrAdminHTTPClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Executes an action or a command in SOLR using REST API 
 * 
 * @param httpClient HTTP Client to be used for the invocation
 * @param url Complete URL of SOLR REST API Endpoint
 * @return A JSON Object including SOLR response
 * @throws UnsupportedEncodingException
 */
protected JSONObject getOperation(HttpClient httpClient, String url) throws UnsupportedEncodingException 
{

    GetMethod get = new GetMethod(url);
    
    try {
        
        httpClient.executeMethod(get);
        if(get.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || get.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
        {
            Header locationHeader = get.getResponseHeader("location");
            if (locationHeader != null)
            {
                String redirectLocation = locationHeader.getValue();
                get.setURI(new URI(redirectLocation, true));
                httpClient.executeMethod(get);
            }
        }
        if (get.getStatusCode() != HttpServletResponse.SC_OK)
        {
            throw new LuceneQueryParserException("Request failed " + get.getStatusCode() + " " + url.toString());
        }

        Reader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), get.getResponseCharSet()));
        JSONObject json = new JSONObject(new JSONTokener(reader));
        return json;
        
    }
    catch (IOException | JSONException e) 
    {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } 
    finally 
    {
        get.releaseConnection();
    }
}
 
Example 4
Source File: AbstractSolrQueryHTTPClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body) throws UnsupportedEncodingException,
IOException, HttpException, URIException, JSONException
{
    PostMethod post = new PostMethod(url);
    if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER)
    {
        post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    }
    StringRequestEntity requestEntity = new StringRequestEntity(body.toString(), "application/json", "UTF-8");
    post.setRequestEntity(requestEntity);
    try
    {
        httpClient.executeMethod(post);
        if(post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
        {
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null)
            {
                String redirectLocation = locationHeader.getValue();
                post.setURI(new URI(redirectLocation, true));
                httpClient.executeMethod(post);
            }
        }
        if (post.getStatusCode() != HttpServletResponse.SC_OK)
        {
            throw new LuceneQueryParserException("Request failed " + post.getStatusCode() + " " + url.toString());
        }

        Reader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
        // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
        JSONObject json = new JSONObject(new JSONTokener(reader));
        return json;
    }
    finally
    {
        post.releaseConnection();
    }
}
 
Example 5
Source File: HTTPUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
/**
 * @param responseCode
 * @return
 */
public static boolean verifyResponseCode(final int responseCode) {
    switch (responseCode) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            return true;
        default:
            return false;
    }
}
 
Example 6
Source File: HTTPUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
/**
 * @param responseCode
 * @return
 */
public static boolean verifyResponseCode(int responseCode) {
    switch (responseCode) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_MOVED_TEMPORARILY:
            return true;
        default:
            return false;

    }
}
 
Example 7
Source File: MSNPropertyHandler.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
*/
  @SuppressWarnings({ "unchecked" })
  @Override
  public boolean isValid(final FormItem formItem, final Map formContext) {
      boolean result;
      final TextElement textElement = (TextElement) formItem;

      if (StringHelper.containsNonWhitespace(textElement.getValue())) {

          // Use an HttpClient to fetch a profile information page from MSN.
          final HttpClient httpClient = HttpClientFactory.getHttpClientInstance();
          final HttpClientParams httpClientParams = httpClient.getParams();
          httpClientParams.setConnectionManagerTimeout(2500);
          httpClient.setParams(httpClientParams);
          final HttpMethod httpMethod = new GetMethod(MSN_NAME_VALIDATION_URL);
          final NameValuePair idParam = new NameValuePair(MSN_NAME_URL_PARAMETER, textElement.getValue());
          httpMethod.setQueryString(new NameValuePair[] { idParam });
          // Don't allow redirects since otherwise, we won't be able to get the correct status
          httpMethod.setFollowRedirects(false);
          try {
              // Get the user profile page
              httpClient.executeMethod(httpMethod);
              final int httpStatusCode = httpMethod.getStatusCode();
              // Looking at the HTTP status code tells us whether a user with the given MSN name exists.
              if (httpStatusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
                  // If the user exists, we get a 301...
                  result = true;
              } else if (httpStatusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                  // ...and if the user doesn't exist, MSN sends a 500.
                  textElement.setErrorKey("form.name.msn.error", null);
                  result = false;
              } else {
                  // For HTTP status codes other than 301 and 500 we will assume that the given MSN name is valid, but inform the user about this.
                  textElement.setExampleKey("form.example.msnname.notvalidated", null);
                  log.warn("MSN name validation: Expected HTTP status 301 or 500, but got " + httpStatusCode);
                  result = true;
              }
          } catch (final Exception e) {
              // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user about
              // this.
              textElement.setExampleKey("form.example.msnname.notvalidated", null);
              log.warn("MSN name validation: Exception: " + e.getMessage());
              result = true;
          }
      } else {
          result = true;
      }
      return result;
  }
 
Example 8
Source File: MSNPropertyHandler.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
*/
  @SuppressWarnings({ "unchecked" })
  @Override
  public boolean isValid(final FormItem formItem, final Map formContext) {
      boolean result;
      final TextElement textElement = (TextElement) formItem;

      if (StringHelper.containsNonWhitespace(textElement.getValue())) {

          // Use an HttpClient to fetch a profile information page from MSN.
          final HttpClient httpClient = HttpClientFactory.getHttpClientInstance();
          final HttpClientParams httpClientParams = httpClient.getParams();
          httpClientParams.setConnectionManagerTimeout(2500);
          httpClient.setParams(httpClientParams);
          final HttpMethod httpMethod = new GetMethod(MSN_NAME_VALIDATION_URL);
          final NameValuePair idParam = new NameValuePair(MSN_NAME_URL_PARAMETER, textElement.getValue());
          httpMethod.setQueryString(new NameValuePair[] { idParam });
          // Don't allow redirects since otherwise, we won't be able to get the correct status
          httpMethod.setFollowRedirects(false);
          try {
              // Get the user profile page
              httpClient.executeMethod(httpMethod);
              final int httpStatusCode = httpMethod.getStatusCode();
              // Looking at the HTTP status code tells us whether a user with the given MSN name exists.
              if (httpStatusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
                  // If the user exists, we get a 301...
                  result = true;
              } else if (httpStatusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                  // ...and if the user doesn't exist, MSN sends a 500.
                  textElement.setErrorKey("form.name.msn.error", null);
                  result = false;
              } else {
                  // For HTTP status codes other than 301 and 500 we will assume that the given MSN name is valid, but inform the user about this.
                  textElement.setExampleKey("form.example.msnname.notvalidated", null);
                  log.warn("MSN name validation: Expected HTTP status 301 or 500, but got " + httpStatusCode);
                  result = true;
              }
          } catch (final Exception e) {
              // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user about
              // this.
              textElement.setExampleKey("form.example.msnname.notvalidated", null);
              log.warn("MSN name validation: Exception: " + e.getMessage());
              result = true;
          }
      } else {
          result = true;
      }
      return result;
  }