Java Code Examples for org.apache.commons.httpclient.Header#getValue()

The following examples show how to use org.apache.commons.httpclient.Header#getValue() . 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: Filter5HttpProxy.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * 处理请求自动转向问题
 * </p>
 * @param appServer
 * @param response
 * @param client
 * @param httppost
 * @throws IOException
 * @throws BusinessServletException
 */
private void dealWithRedirect(AppServer appServer, HttpServletResponse response, HttpClient client, HttpMethod httpMethod) 
           throws IOException, BusinessServletException {
    
	Header location = httpMethod.getResponseHeader("location");
	httpMethod.releaseConnection();
	
	if ( location == null || EasyUtils.isNullOrEmpty(location.getValue()) ) {
		throw new BusinessServletException(appServer.getName() + "(" + appServer.getCode() + ")返回错误的自动转向地址信息");
	}
	
	String redirectURI = location.getValue();
       GetMethod redirect = new GetMethod(redirectURI);
       try {
           client.executeMethod(redirect); // 发送Get请求
           
           transmitResponse(appServer, response, client, redirect);
           
       } finally {
           redirect.releaseConnection();
       }
}
 
Example 2
Source File: CoursesResourcesFoldersITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetFileDeep() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final URI uri = UriBuilder.fromUri(getCourseFolderURI()).path("SubDir").path("SubSubDir").path("SubSubSubDir").path("3_singlepage.html").build();
    final GetMethod method = createGet(uri, "*/*", true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);

    final String body = method.getResponseBodyAsString();
    assertNotNull(body);
    assertTrue(body.startsWith("<html>"));

    String contentType = null;
    for (final Header header : method.getResponseHeaders()) {
        if ("Content-Type".equals(header.getName())) {
            contentType = header.getValue();
            break;
        }
    }
    assertNotNull(contentType);
    assertEquals("text/html", contentType);
}
 
Example 3
Source File: JunkUtils.java    From http4e with Apache License 2.0 6 votes vote down vote up
public static String getHdToken(String url, String md){
      final HttpClient client = new HttpClient();      
      PostMethod post = new PostMethod(url);
      post.setRequestHeader("content-type", "application/x-www-form-urlencoded");
      post.setParameter("v", md);
      
      post.setApacheHttpListener(httpListener);
      try {
         HttpUtils.execute(client, post, responseReader);
         Header header = post.getResponseHeader("hd-token");
         if(header != null){
//            System.out.println("hd-token:" + header.getValue() + "'");
            return header.getValue();
         }
      } catch (Exception ignore) {
         ExceptionHandler.handle(ignore);
      } finally {
         if(post != null) post.releaseConnection();
      }
      return null;
   }
 
Example 4
Source File: OptionsMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <p>
 * This implementation will parse the <tt>Allow</tt> header to obtain 
 * the set of methods supported by the resource identified by the Request-URI.
 * </p>
 *
 * @param state the {@link HttpState state} information associated with this method
 * @param conn the {@link HttpConnection connection} used to execute
 *        this HTTP method
 *
 * @see #readResponse
 * @see #readResponseHeaders
 * @since 2.0
 */
protected void processResponseHeaders(HttpState state, HttpConnection conn) {
    LOG.trace("enter OptionsMethod.processResponseHeaders(HttpState, HttpConnection)");

    Header allowHeader = getResponseHeader("allow");
    if (allowHeader != null) {
        String allowHeaderValue = allowHeader.getValue();
        StringTokenizer tokenizer =
            new StringTokenizer(allowHeaderValue, ",");
        while (tokenizer.hasMoreElements()) {
            String methodAllowed =
                tokenizer.nextToken().trim().toUpperCase();
            methodsAllowed.addElement(methodAllowed);
        }
    }
}
 
Example 5
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 6 votes vote down vote up
/**
 * 回馈的结果为RP_NO_CHANGE,则整个流程为:<br>
 * 1.检查缓存中的MD5码与返回的MD5码是否一致,如果不一致,则删除缓存行。重新再次查询。<br>
 * 2.如果MD5码一致,则直接返回NULL<br>
 */
private String getNotModified(String dataId, CacheData cacheData, HttpMethod httpMethod) {
    Header md5Header = httpMethod.getResponseHeader(Constants.CONTENT_MD5);
    if (null == md5Header) {
        throw new RuntimeException("RP_NO_CHANGE返回的结果中没有MD5码");
    }
    String md5 = md5Header.getValue();
    if (!cacheData.getMd5().equals(md5)) {
        String lastMd5 = cacheData.getMd5();
        cacheData.setMd5(Constants.NULL);
        cacheData.setLastModifiedHeader(Constants.NULL);
        throw new RuntimeException("MD5码校验对比出错,DataID为:[" + dataId + "]上次MD5为:[" + lastMd5 + "]本次MD5为:[" + md5
                + "]");
    }

    cacheData.setMd5(md5);
    changeSpacingInterval(httpMethod);
    if (log.isInfoEnabled()) {
        log.info("DataId: " + dataId + ", 对应的configInfo没有变化");
    }
    return null;
}
 
Example 6
Source File: CoursesResourcesFoldersITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetFileDeep() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final URI uri = UriBuilder.fromUri(getCourseFolderURI()).path("SubDir").path("SubSubDir").path("SubSubSubDir").path("3_singlepage.html").build();
    final GetMethod method = createGet(uri, "*/*", true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);

    final String body = method.getResponseBodyAsString();
    assertNotNull(body);
    assertTrue(body.startsWith("<html>"));

    String contentType = null;
    for (final Header header : method.getResponseHeaders()) {
        if ("Content-Type".equals(header.getName())) {
            contentType = header.getValue();
            break;
        }
    }
    assertNotNull(contentType);
    assertEquals("text/html", contentType);
}
 
Example 7
Source File: ApacheHttp31SLR.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
private void acquireLength() throws URISyntaxException, HttpException, IOException {
	HttpMethod head = new HeadMethod(url);
	int code = http.executeMethod(head);
	if(code != 200) {
		throw new IOException("Unable to retrieve from " + url);
	}
	Header lengthHeader = head.getResponseHeader(CONTENT_LENGTH);
	if(lengthHeader == null) {
		throw new IOException("No Content-Length header for " + url);
	}
	String val = lengthHeader.getValue();
	try {
		length = Long.parseLong(val);
	} catch(NumberFormatException e) {
		throw new IOException("Bad Content-Length value " +url+ ": " + val);
	}
}
 
Example 8
Source File: HTTPMetadataProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Records the ETag and Last-Modified headers, from the response, if they are present.
 * 
 * @param getMethod GetMethod containing a valid HTTP response
 */
protected void processConditionalRetrievalHeaders(GetMethod getMethod) {
    Header httpHeader = getMethod.getResponseHeader("ETag");
    if (httpHeader != null) {
        cachedMetadataETag = httpHeader.getValue();
    }

    httpHeader = getMethod.getResponseHeader("Last-Modified");
    if (httpHeader != null) {
        cachedMetadataLastModified = httpHeader.getValue();
    }
}
 
Example 9
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public String getHeaderField(String key) throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader(key);

  if (head == null) {
    return null;
  }

  return head.getValue();
}
 
Example 10
Source File: ProxyFilter.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Will create the method and execute it. After this the method is sent to a
 * ResponseHandler that is returned.
 * 
 * @param httpRequest
 *            Request we are receiving from the client
 * @param url
 *            The location we are proxying to
 * @return A ResponseHandler that can be used to write the response
 * @throws MethodNotAllowedException
 *             If the method specified by the request isn't handled
 * @throws IOException
 *             When there is a problem with the streams
 * @throws HttpException
 *             The httpclient can throw HttpExcetion when executing the
 *             method
 */
ResponseHandler executeRequest(HttpServletRequest httpRequest, String url)
        throws MethodNotAllowedException, IOException, HttpException {
    RequestHandler requestHandler = RequestHandlerFactory
            .createRequestMethod(httpRequest.getMethod());

    HttpMethod method = requestHandler.process(httpRequest, url);
    method.setFollowRedirects(false);

    /*
     * Why does method.validate() return true when the method has been
     * aborted? I mean, if validate returns true the API says that means
     * that the method is ready to be executed. TODO I don't like doing type
     * casting here, see above.
     */
    if (!((HttpMethodBase) method).isAborted()) {
        httpClient.executeMethod(method);

        if (method.getStatusCode() == 405) {
            Header allow = method.getResponseHeader("allow");
            String value = allow.getValue();
            throw new MethodNotAllowedException(
                    "Status code 405 from server",
                    AllowedMethodHandler.processAllowHeader(value));
        }
    }

    return ResponseHandlerFactory.createResponseHandler(method);
}
 
Example 11
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public String getType() {
  try {
    HttpMethod res = getResult(true);
    Header head = res.getResponseHeader("Content-Type") ;

    if (head == null) {
      return null;
    }

    return head.getValue();
  } catch (IOException e) {
    return null;
  }
}
 
Example 12
Source File: ResponseFilter.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
protected void copyHeadersFromEndpoint(ProxyContext context)
{
    HttpServletResponse clientResponse = FlexContext.getHttpResponse();

    if (clientResponse != null)
    {
        Header[] headers = context.getHttpMethod().getResponseHeaders();
        for (int i = 0; i < headers.length; i++)
        {
            Header header = headers[i];
            String name = header.getName();
            String value = header.getValue();
            if (ResponseUtil.ignoreHeader(name, context))
            {
                continue;
            }

            if ((name != null) && (value != null))
            {
                clientResponse.addHeader(name, value);
                if (Log.isInfo())
                {
                    Log.getLogger(HTTPProxyService.LOG_CATEGORY).debug("-- Header in response: " + name + " : " + value);
                }
            }
        }
        // set Pragma needed for ATG on HTTPS
        clientResponse.setHeader("Pragma", "public");
    }
}
 
Example 13
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Login the HttpClient based on the session cookie
 * 
 * @param username
 * @param password
 * @param c
 * @throws HttpException
 * @throws IOException
 */
public String loginWithToken(final String username, final String password, final HttpClient c) throws HttpException, IOException {
    final URI uri = UriBuilder.fromUri(getContextURI()).path("auth").path(username).queryParam("password", password).build();
    final GetMethod method = new GetMethod(uri.toString());
    final int response = c.executeMethod(method);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    assertTrue(response == 200);
    assertTrue(body != null && body.length() > "<hello></hello>".length());
    final Header securityToken = method.getResponseHeader(RestSecurityHelper.SEC_TOKEN);
    assertTrue(securityToken != null && StringHelper.containsNonWhitespace(securityToken.getValue()));
    return securityToken == null ? null : securityToken.getValue();
}
 
Example 14
Source File: UcsHttpClient.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public String call(String xml) {
    PostMethod post = new PostMethod(url);
    post.setRequestEntity(new StringRequestEntity(xml));
    post.setRequestHeader("Content-type", "text/xml");
    //post.setFollowRedirects(true);
    try {
        int result = client.executeMethod(post);
        if (result == 302) {
            // Handle HTTPS redirect
            // Ideal way might be to configure from add manager API
            // for using either HTTP / HTTPS
            // Allow only one level of redirect
            String redirectLocation;
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
            } else {
                throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager");
            }
            post.setURI(new URI(redirectLocation));
            result = client.executeMethod(post);
        }
        // Check for errors
        if (result != 200) {
            throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString());
        }
        String res = post.getResponseBodyAsString();
        if (res.contains("errorCode")) {
            String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res);
            throw new CloudRuntimeException(err);
        }
        return res;
    } catch (Exception e) {
        throw new CloudRuntimeException(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
}
 
Example 15
Source File: ApacheHttp31SLR.java    From webarchive-commons with Apache License 2.0 5 votes vote down vote up
protected String getHeader(String header) throws URISyntaxException, HttpException, IOException {
	HttpMethod head = new HeadMethod(url);
	int code = http.executeMethod(head);
	if(code != 200) {
		throw new IOException("Unable to retrieve from " + url);
	}
	Header theHeader = head.getResponseHeader(header);
	if(theHeader == null) {
		throw new IOException("No " + header + " header for " + url);
	}
	String val = theHeader.getValue();
	return val;
}
 
Example 16
Source File: BrowseController.java    From webcurator with Apache License 2.0 5 votes vote down vote up
private String getHeaderValue(Header[] headers, String key) {
	if (headers != null) {
		for (Header h : headers) {
			if (key.equalsIgnoreCase(h.getName())) {
				return h.getValue();
			}
		}
	}
	return null;
}
 
Example 17
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
private void fetchFirstResource(final Identity ident) {

        final TURequest tureq = new TURequest(); // config, ureq);
        tureq.setContentType(null); // not used
        tureq.setMethod("GET");
        tureq.setParameterMap(Collections.EMPTY_MAP);
        tureq.setQueryString(query);
        if (startUri != null) {
            if (startUri.startsWith("/")) {
                tureq.setUri(startUri);
            } else {
                tureq.setUri("/" + startUri);
            }
        }

        // if (allowedToSendPersonalHeaders) {
        final String userName = ident.getName();
        final User u = ident.getUser();
        final String lastName = getUserService().getUserProperty(u, UserConstants.LASTNAME, loc);
        final String firstName = getUserService().getUserProperty(u, UserConstants.FIRSTNAME, loc);
        final String email = getUserService().getUserProperty(u, UserConstants.EMAIL, loc);

        tureq.setEmail(email);
        tureq.setFirstName(firstName);
        tureq.setLastName(lastName);
        tureq.setUserName(userName);
        // }

        final HttpMethod meth = fetch(tureq, httpClientInstance);
        if (meth == null) {
            setFetchError();
        } else {

            final Header responseHeader = meth.getResponseHeader("Content-Type");
            String mimeType;
            if (responseHeader == null) {
                setFetchError();
                mimeType = null;
            } else {
                mimeType = responseHeader.getValue();
            }

            if (mimeType != null && mimeType.startsWith("text/html")) {
                // we have html content, let doDispatch handle it for
                // inline rendering, update hreq for next content request
                String body;
                try {
                    body = meth.getResponseBodyAsString();
                } catch (final IOException e) {
                    log.warn("Problems when tunneling URL::" + tureq.getUri(), e);
                    htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": Unknown transfer problem '";
                    return;
                }
                final SimpleHtmlParser parser = new SimpleHtmlParser(body);
                if (!parser.isValidHtml()) { // this is not valid HTML, deliver
                    // asynchronuous
                }
                meth.releaseConnection();
                htmlHead = parser.getHtmlHead();
                jsOnLoad = parser.getJsOnLoad();
                htmlContent = parser.getHtmlContent();
            } else {
                htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": mime type was '" + mimeType + "' but expected 'text/html'. Response header was '"
                        + responseHeader + "'.";
            }
        }
    }
 
Example 18
Source File: HadoopStatusGetter.java    From Kylin with Apache License 2.0 4 votes vote down vote up
private String getHttpResponse(String url) throws IOException {
    HttpClient client = new HttpClient();

    String response = null;
    while (response == null) { // follow redirects via 'refresh'
        if (url.startsWith("https://")) {
            registerEasyHttps();
        }
        if (url.contains("anonymous=true") == false) {
            url += url.contains("?") ? "&" : "?";
            url += "anonymous=true";
        }

        HttpMethod get = new GetMethod(url);
        try {
            client.executeMethod(get);

            String redirect = null;
            Header h = get.getResponseHeader("Refresh");
            if (h != null) {
                String s = h.getValue();
                int cut = s.indexOf("url=");
                if (cut >= 0) {
                    redirect = s.substring(cut + 4);
                }
            }

            if (redirect == null) {
                response = get.getResponseBodyAsString();
                log.debug("Job " + mrJobId + " get status check result.\n");
            } else {
                url = redirect;
                log.debug("Job " + mrJobId + " check redirect url " + url + ".\n");
            }
        } finally {
            get.releaseConnection();
        }
    }

    return response;
}
 
Example 19
Source File: BaseWebScriptTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public String getHeader(String name)
{
    Header header = method.getResponseHeader(name);
    return (header != null) ? header.getValue() : null;
}
 
Example 20
Source File: HttpRequestMediaResource.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
*/
  @Override
  public Long getSize() {
      Header h = meth.getResponseHeader("Content-Length");
      return h == null ? null : new Long(h.getValue());
  }