Java Code Examples for org.apache.commons.httpclient.HttpMethod#getResponseHeader()

The following examples show how to use org.apache.commons.httpclient.HttpMethod#getResponseHeader() . 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: 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 2
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 3
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 4
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public int getHeaderFieldInt(String key, int def) throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader(key);

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

  try {
    return Integer.parseInt(head.getValue());
  } catch (NumberFormatException e) {
    return def;
  }
}
 
Example 5
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public long getExpiration() throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader("Expires");

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

  try {
    return DateUtil.parseDate(head.getValue()).getTime();
  } catch (DateParseException e) {
    return 0;
  }
}
 
Example 6
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public long getDate() throws IOException {
  final HttpMethod res = getResult(true);
  final Header head = res.getResponseHeader("Date");

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

  try {
    return DateUtil.parseDate(head.getValue()).getTime();
  } catch (DateParseException e) {
    return 0;
  }
}
 
Example 7
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 5 votes vote down vote up
/**
 * 查看是否为压缩的内容
 * 
 * @param httpMethod
 * @return
 */
boolean isZipContent(HttpMethod httpMethod) {
    if (null != httpMethod.getResponseHeader(Constants.CONTENT_ENCODING)) {
        String acceptEncoding = httpMethod.getResponseHeader(Constants.CONTENT_ENCODING).getValue();
        if (acceptEncoding.toLowerCase().indexOf("gzip") > -1) {
            return true;
        }
    }
    return false;
}
 
Example 8
Source File: MorphologicalServiceDEImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
private InputStream retreiveXMLReply(String partOfSpeech, String word) {
    HttpClient client = HttpClientFactory.getHttpClientInstance();
    HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
    NameValuePair posValues = new NameValuePair(PART_OF_SPEECH_PARAM, partOfSpeech);
    NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
    if (log.isDebugEnabled()) {
        String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + PART_OF_SPEECH_PARAM + "=" + partOfSpeech + "&" + GLOSS_TERM_PARAM + "=" + word;
        log.debug("Send GET request to morph-service with URL: " + url);
    }
    method.setQueryString(new NameValuePair[] { posValues, wordValues });
    try {
        client.executeMethod(method);
        int status = method.getStatusCode();
        if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
            if (log.isDebugEnabled()) {
                log.debug("got a valid reply!");
            }
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            log.error("Morphological Service unavailable (404)::" + method.getStatusLine().toString());
        } else {
            log.error("Unexpected HTTP Status::" + method.getStatusLine().toString());
        }
    } catch (Exception e) {
        log.error("Unexpected exception trying to get flexions!", e);
    }
    Header responseHeader = method.getResponseHeader("Content-Type");
    if (responseHeader == null) {
        // error
        log.error("URL not found!");
    }
    HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
    InputStream inputStream = mr.getInputStream();

    return inputStream;
}
 
Example 9
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 5 votes vote down vote up
/**
 * 查看是否为压缩的内容
 * 
 * @param httpMethod
 * @return
 */
boolean isZipContent(HttpMethod httpMethod) {
    if (null != httpMethod.getResponseHeader(Constants.CONTENT_ENCODING)) {
        String acceptEncoding = httpMethod.getResponseHeader(Constants.CONTENT_ENCODING).getValue();
        if (acceptEncoding.toLowerCase().indexOf("gzip") > -1) {
            return true;
        }
    }
    return false;
}
 
Example 10
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 11
Source File: DefaultEncryptionUtils.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Decode cipher algorithm parameters from the HTTP method
 * 
 * @param method HttpMethod
 * @return decoded algorithm parameters
 * @throws IOException
 */
protected AlgorithmParameters decodeAlgorithmParameters(HttpMethod method) throws IOException
{
    Header header = method.getResponseHeader(HEADER_ALGORITHM_PARAMETERS);
    if(header != null)
    {
        byte[] algorithmParams = Base64.decode(header.getValue());
        AlgorithmParameters algorithmParameters  = encryptor.decodeAlgorithmParameters(algorithmParams);
        return algorithmParameters;
    }
    else
    {
        return null;
    }
}
 
Example 12
Source File: DefaultEncryptionUtils.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the timestamp on the HTTP response
 * 
 * @param method HttpMethod
 * @return timestamp (ms, in UNIX time)
 * @throws IOException
 */
protected Long getResponseTimestamp(HttpMethod method) throws IOException
{
    Header header = method.getResponseHeader(HEADER_TIMESTAMP);
    if(header != null)
    {
        return Long.valueOf(header.getValue());
    }
    else
    {
        return null;
    }
}
 
Example 13
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public String getEncoding() { // throws IOException
  try {
    HttpMethod res = getResult(true);
    Header head = res.getResponseHeader("Content-Encoding");

    if (head != null) {
      return head.getValue();
    }

    return null;
  } catch (IOException e) {
    return null;
  }
}
 
Example 14
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
*/
  @Override
  public MediaResource getAsyncMediaResource(final UserRequest ureq) {

      final String moduleURI = ureq.getModuleURI();
      // FIXME:fj: can we distinguish between a ../ call an a click to another component?
      // now works for start uri's like /demo/tunneldemo.php but when in tunneldemo.php
      // a link is used like ../ this link does not work (moduleURI is null). if i use
      // ../index.php instead everything works as expected
      if (moduleURI == null) { // after a click on some other component e.g.
          if (!firstCall) {
              return null;
          }
          firstCall = false; // reset first call
      }

      final TURequest tureq = new TURequest(config, ureq);

      // if (allowedToSendPersonalHeaders) {
      final String userName = ureq.getIdentity().getName();
      final User u = ureq.getIdentity().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();
          return null;
      }

      final Header responseHeader = meth.getResponseHeader("Content-Type");
      if (responseHeader == null) {
          setFetchError();
          return null;
      }

      final String 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);
              return null;
          }
          final SimpleHtmlParser parser = new SimpleHtmlParser(body);
          if (!parser.isValidHtml()) { // this is not valid HTML, deliver
              // asynchronuous
              return new HttpRequestMediaResource(meth);
          }
          meth.releaseConnection();
          htmlHead = parser.getHtmlHead();
          jsOnLoad = parser.getJsOnLoad();
          htmlContent = parser.getHtmlContent();
          setDirty(true);
      } else {
          return new HttpRequestMediaResource(meth); // this is a async browser
      }
      // refetch
      return null;
  }
 
Example 15
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 4 votes vote down vote up
/**
 * 回馈的结果为RP_OK,则整个流程为:<br>
 * 1.获取配置信息,如果配置信息为空或者抛出异常,则抛出运行时异常<br>
 * 2.检测配置信息是否符合回馈结果中的MD5码,不符合,则再次获取配置信息,并记录日志<br>
 * 3.符合,则存储LastModified信息和MD5码,调整查询的间隔时间,将获取的配置信息发送给客户的监听器<br>
 */
private String getSuccess(String dataId, String group, CacheData cacheData, HttpMethod httpMethod) {
    String configInfo = Constants.NULL;
    configInfo = getContent(httpMethod);
    if (null == configInfo) {
        throw new RuntimeException("RP_OK获取了错误的配置信息");
    }

    Header md5Header = httpMethod.getResponseHeader(Constants.CONTENT_MD5);
    if (null == md5Header) {
        throw new RuntimeException("RP_OK返回的结果中没有MD5码, " + configInfo);
    }
    String md5 = md5Header.getValue();
    if (!checkContent(configInfo, md5)) {
        throw new RuntimeException("配置信息的MD5码校验出错,DataID为:[" + dataId + "]配置信息为:[" + configInfo + "]MD5为:[" + md5
                + "]");
    }

    Header lastModifiedHeader = httpMethod.getResponseHeader(Constants.LAST_MODIFIED);
    if (null == lastModifiedHeader) {
        throw new RuntimeException("RP_OK返回的结果中没有lastModifiedHeader");
    }
    String lastModified = lastModifiedHeader.getValue();

    cacheData.setMd5(md5);
    cacheData.setLastModifiedHeader(lastModified);

    changeSpacingInterval(httpMethod);

    // 设置到本地cache
    String key = makeCacheKey(dataId, group);
    contentCache.put(key, configInfo);

    // 记录接收到的数据
    StringBuilder buf = new StringBuilder();
    buf.append("dataId=").append(dataId);
    buf.append(" ,group=").append(group);
    buf.append(" ,content=").append(configInfo);
    dataLog.info(buf.toString());

    return configInfo;
}
 
Example 16
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 17
Source File: OlatJerseyTestCase.java    From olat with Apache License 2.0 4 votes vote down vote up
public String getToken(final HttpMethod method) {
    final Header header = method.getResponseHeader(RestSecurityHelper.SEC_TOKEN);
    return header == null ? null : header.getValue();
}
 
Example 18
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
*/
  @Override
  public MediaResource getAsyncMediaResource(final UserRequest ureq) {

      final String moduleURI = ureq.getModuleURI();
      // FIXME:fj: can we distinguish between a ../ call an a click to another component?
      // now works for start uri's like /demo/tunneldemo.php but when in tunneldemo.php
      // a link is used like ../ this link does not work (moduleURI is null). if i use
      // ../index.php instead everything works as expected
      if (moduleURI == null) { // after a click on some other component e.g.
          if (!firstCall) {
              return null;
          }
          firstCall = false; // reset first call
      }

      final TURequest tureq = new TURequest(config, ureq);

      // if (allowedToSendPersonalHeaders) {
      final String userName = ureq.getIdentity().getName();
      final User u = ureq.getIdentity().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();
          return null;
      }

      final Header responseHeader = meth.getResponseHeader("Content-Type");
      if (responseHeader == null) {
          setFetchError();
          return null;
      }

      final String 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);
              return null;
          }
          final SimpleHtmlParser parser = new SimpleHtmlParser(body);
          if (!parser.isValidHtml()) { // this is not valid HTML, deliver
              // asynchronuous
              return new HttpRequestMediaResource(meth);
          }
          meth.releaseConnection();
          htmlHead = parser.getHtmlHead();
          jsOnLoad = parser.getJsOnLoad();
          htmlContent = parser.getHtmlContent();
          setDirty(true);
      } else {
          return new HttpRequestMediaResource(meth); // this is a async browser
      }
      // refetch
      return null;
  }
 
Example 19
Source File: HttpClientFeedFetcher.java    From rome with Apache License 2.0 4 votes vote down vote up
private SyndFeedInfo buildSyndFeedInfo(final URL feedUrl, final String urlStr, final HttpMethod method, SyndFeed feed, final int statusCode)
        throws MalformedURLException {

    SyndFeedInfo syndFeedInfo;
    syndFeedInfo = new SyndFeedInfo();

    // this may be different to feedURL because of 3XX redirects
    syndFeedInfo.setUrl(new URL(urlStr));
    syndFeedInfo.setId(feedUrl.toString());

    final Header imHeader = method.getResponseHeader("IM");
    if (imHeader != null && imHeader.getValue().contains("feed") && isUsingDeltaEncoding()) {

        final FeedFetcherCache cache = getFeedInfoCache();

        if (cache != null && statusCode == 226) {
            // client is setup to use http delta encoding and the server supports it and has
            // returned a delta encoded response. This response only includes new items
            final SyndFeedInfo cachedInfo = cache.getFeedInfo(feedUrl);

            if (cachedInfo != null) {
                final SyndFeed cachedFeed = cachedInfo.getSyndFeed();

                // set the new feed to be the orginal feed plus the new items
                feed = combineFeeds(cachedFeed, feed);
            }
        }
    }

    final Header lastModifiedHeader = method.getResponseHeader("Last-Modified");
    if (lastModifiedHeader != null) {
        syndFeedInfo.setLastModified(lastModifiedHeader.getValue());
    }

    final Header eTagHeader = method.getResponseHeader("ETag");
    if (eTagHeader != null) {
        syndFeedInfo.setETag(eTagHeader.getValue());
    }

    syndFeedInfo.setSyndFeed(feed);

    return syndFeedInfo;
}
 
Example 20
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;
}