List of usage examples for org.apache.commons.httpclient HttpMethod getResponseHeader
public abstract Header getResponseHeader(String paramString);
From source file:org.olat.core.commons.modules.glossary.morphService.MorphologicalServiceFRImpl.java
private InputStream retreiveXMLReply(String word) { HttpClient client = HttpClientFactory.getHttpClientInstance(); HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS); NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word); if (isLogDebugEnabled()) { String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + GLOSS_TERM_PARAM + "=" + word; logDebug("Send GET request to morph-service with URL: " + url); }// w w w . j av a2s . c om method.setQueryString(new NameValuePair[] { wordValues }); try { client.executeMethod(method); int status = method.getStatusCode(); if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) { if (isLogDebugEnabled()) { logDebug("got a valid reply!"); } } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) { logError("Morphological Service unavailable (404)::" + method.getStatusLine().toString(), null); } else { logError("Unexpected HTTP Status::" + method.getStatusLine().toString(), null); } } catch (Exception e) { logError("Unexpected exception trying to get flexions!", e); } Header responseHeader = method.getResponseHeader("Content-Type"); if (responseHeader == null) { // error logError("URL not found!", null); } HttpRequestMediaResource mr = new HttpRequestMediaResource(method); InputStream inputStream = mr.getInputStream(); return inputStream; }
From source file:org.olat.modules.tu.IframeTunnelController.java
/** * Constructor for a tunnel component wrapper controller * //from w ww. ja v a2 s.c o m * @param ureq the userrequest * @param wControl the windowcontrol * @param config the module configuration */ public IframeTunnelController(final UserRequest ureq, final WindowControl wControl, final ModuleConfiguration config) { super(ureq, wControl); // use iframe translator for generic iframe title text setTranslator(Util.createPackageTranslator(IFrameDisplayController.class, ureq.getLocale())); this.config = config; // configuration.... final int configVersion = config.getConfigurationVersion(); // since config version 1 final String proto = (String) config.get(TUConfigForm.CONFIGKEY_PROTO); final String host = (String) config.get(TUConfigForm.CONFIGKEY_HOST); final Integer port = (Integer) config.get(TUConfigForm.CONFIGKEY_PORT); final String user = (String) config.get(TUConfigForm.CONFIGKEY_USER); final String startUri = (String) config.get(TUConfigForm.CONFIGKEY_URI); final String pass = (String) config.get(TUConfigForm.CONFIGKEY_PASS); String firstQueryString = null; if (configVersion == 2) { // query string is available since config version 2 firstQueryString = (String) config.get(TUConfigForm.CONFIGKEY_QUERY); } final boolean usetunnel = config.getBooleanSafe(TUConfigForm.CONFIG_TUNNEL); myContent = createVelocityContainer("iframe_index"); if (!usetunnel) { // display content directly final String rawurl = TUConfigForm.getFullURL(proto, host, port, startUri, firstQueryString).toString(); myContent.contextPut("url", rawurl); } else { // tunnel final Identity ident = ureq.getIdentity(); if (user != null && user.length() > 0) { httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, user, pass); } else { httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, null, null); } final Locale loc = ureq.getLocale(); final Mapper mapper = new Mapper() { @Override public MediaResource handle(final String relPath, final HttpServletRequest hreq) { MediaResource mr = null; final String method = hreq.getMethod(); String uri = relPath; HttpMethod meth = null; if (uri == null) { uri = (startUri == null) ? "" : startUri; } if (uri.length() > 0 && uri.charAt(0) != '/') { uri = "/" + uri; } // String contentType = hreq.getContentType(); // if (allowedToSendPersonalHeaders) { final String userName = ident.getName(); final User u = ident.getUser(); final String lastName = u.getProperty(UserConstants.LASTNAME, loc); final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc); final String email = u.getProperty(UserConstants.EMAIL, loc); if (method.equals("GET")) { final GetMethod cmeth = new GetMethod(uri); final String queryString = hreq.getQueryString(); if (queryString != null) { cmeth.setQueryString(queryString); } meth = cmeth; // if response is a redirect, follow it if (meth == null) { return null; } meth.setFollowRedirects(true); } else if (method.equals("POST")) { // if (contentType == null || contentType.equals("application/x-www-form-urlencoded")) { // regular post, no file upload // } final Map params = hreq.getParameterMap(); final PostMethod pmeth = new PostMethod(uri); final Set postKeys = params.keySet(); for (final Iterator iter = postKeys.iterator(); iter.hasNext();) { final String key = (String) iter.next(); final String vals[] = (String[]) params.get(key); for (int i = 0; i < vals.length; i++) { pmeth.addParameter(key, vals[i]); } meth = pmeth; } if (meth == null) { return null; // Redirects are not supported when using POST method! // See RFC 2616, section 10.3.3, page 62 } } // Add olat specific headers to the request, can be used by external // applications to identify user and to get other params // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py meth.addRequestHeader("X-OLAT-USERNAME", userName); meth.addRequestHeader("X-OLAT-LASTNAME", lastName); meth.addRequestHeader("X-OLAT-FIRSTNAME", firstName); meth.addRequestHeader("X-OLAT-EMAIL", email); boolean ok = false; try { httpClientInstance.executeMethod(meth); ok = true; } catch (final Exception e) { // handle error later } if (!ok) { // error meth.releaseConnection(); return new NotFoundMediaResource(relPath); } // get or post successfully final Header responseHeader = meth.getResponseHeader("Content-Type"); if (responseHeader == null) { // error return new NotFoundMediaResource(relPath); } mr = new HttpRequestMediaResource(meth); return mr; } }; final String amapPath = registerMapper(mapper); String alluri = amapPath + startUri; if (firstQueryString != null) { alluri += "?" + firstQueryString; } myContent.contextPut("url", alluri); } final String frameId = "ifdc" + hashCode(); // for e.g. js use myContent.contextPut("frameId", frameId); putInitialPanel(myContent); }
From source file:org.olat.modules.tu.TunnelComponent.java
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);/*from w w w . j a v a2 s. c om*/ 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 = u.getProperty(UserConstants.LASTNAME, loc); final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc); final String email = u.getProperty(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) { Tracing.logWarn("Problems when tunneling URL::" + tureq.getUri(), e, TunnelComponent.class); 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 + "'."; } } }
From source file:org.olat.modules.tu.TunnelComponent.java
/** * @see org.olat.core.gui.media.AsyncMediaResponsible#getAsyncMediaResource(org.olat.core.gui.UserRequest) */// w w w . j a v a2 s . c o m @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 = u.getProperty(UserConstants.LASTNAME, loc); final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc); final String email = u.getProperty(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) { Tracing.logWarn("Problems when tunneling URL::" + tureq.getUri(), e, TunnelComponent.class); 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; }
From source file:org.olat.test.OlatJerseyTestCase.java
public String getToken(final HttpMethod method) { final Header header = method.getResponseHeader(RestSecurityHelper.SEC_TOKEN); return header == null ? null : header.getValue(); }
From source file:org.openhab.binding.nest.internal.messages.AbstractRequest.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do * not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL. * /* w w w .j a v a2 s . c om*/ * @param httpMethod * the HTTP method to use * @param url * the url to execute (in milliseconds) * @param contentString * the content to be sent to the given <code>url</code> or <code>null</code> if no content should be * sent. * @param contentType * the content type of the given <code>contentString</code> * @return the response body or <code>NULL</code> when the request went wrong */ protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) { HttpClient client = new HttpClient(); HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(HTTP_REQUEST_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey))); } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && contentString != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; InputStream content = new ByteArrayInputStream(contentString.getBytes()); eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } if (logger.isDebugEnabled()) { try { logger.trace("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.trace(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) { // perfectly fine but we cannot expect any answer... return null; } // Manually handle 307 redirects with a little tail recursion if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) { Header[] headers = method.getResponseHeaders("Location"); String newUrl = headers[headers.length - 1].getValue(); return executeUrl(httpMethod, newUrl, contentString, contentType); } if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } InputStream tmpResponseStream = method.getResponseBodyAsStream(); Header encodingHeader = method.getResponseHeader("Content-Encoding"); if (encodingHeader != null) { for (HeaderElement ehElem : encodingHeader.getElements()) { if (ehElem.toString().matches(".*gzip.*")) { tmpResponseStream = new GZIPInputStream(tmpResponseStream); logger.trace("GZipped InputStream from {}", url); } else if (ehElem.toString().matches(".*deflate.*")) { tmpResponseStream = new InflaterInputStream(tmpResponseStream); logger.trace("Deflated InputStream from {}", url); } } } String responseBody = IOUtils.toString(tmpResponseStream); if (!responseBody.isEmpty()) { logger.trace(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }
From source file:org.openhab.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * //from w ww. j a v a2 s .c o m * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) { // perfectly fine but we cannot expect any answer... return null; } if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } InputStream tmpResponseStream = method.getResponseBodyAsStream(); Header encodingHeader = method.getResponseHeader("Content-Encoding"); if (encodingHeader != null) { for (HeaderElement ehElem : encodingHeader.getElements()) { if (ehElem.toString().matches(".*gzip.*")) { tmpResponseStream = new GZIPInputStream(tmpResponseStream); logger.debug("GZipped InputStream from {}", url); } else if (ehElem.toString().matches(".*deflate.*")) { tmpResponseStream = new InflaterInputStream(tmpResponseStream); logger.debug("Deflated InputStream from {}", url); } } } String responseBody = IOUtils.toString(tmpResponseStream); if (!responseBody.isEmpty()) { logger.debug(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }
From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.ConnectMgrVnfm.java
/** * Make connection/* w w w . java2 s .c o m*/ * <br> * * @param vnfmObj * @return * @since NFVO 0.5 */ public int connect(JSONObject vnfmObj, String authModel) { LOG.info("function=connect, msg=enter connect function."); ConnectInfo info = new ConnectInfo(vnfmObj.getString("url"), vnfmObj.getString("userName"), vnfmObj.getString("password"), authModel); HttpMethod httpMethod = null; int statusCode = Constant.INTERNAL_EXCEPTION; try { httpMethod = new HttpRequests.Builder(info.getAuthenticateMode()) .setUrl(info.getUrl(), ParamConstants.CSM_AUTH_CONNECT) .setParams(String.format(ParamConstants.GET_TOKENS_V2, info.getUserName(), info.getUserPwd())) .post().execute(); statusCode = httpMethod.getStatusCode(); String result = httpMethod.getResponseBodyAsString(); LOG.info("connect result:" + result); if (statusCode == HttpStatus.SC_CREATED) { JSONObject accessObj = JSONObject.fromObject(result); JSONObject tokenObj = accessObj.getJSONObject("token"); Header header = httpMethod.getResponseHeader("accessSession"); setAccessSession(header.getValue()); setRoaRand(tokenObj.getString("roa_rand")); statusCode = HttpStatus.SC_OK; } else { LOG.error("connect fail, code:" + statusCode + " re:" + result); } } catch (JSONException e) { LOG.error("function=connect, msg=connect JSONException e={}.", e); } catch (VnfmException e) { LOG.error("function=connect, msg=connect VnfmException e={}.", e); } catch (IOException e) { LOG.error("function=connect, msg=connect IOException e={}.", e); } finally { clearCSMPwd(info); if (httpMethod != null) { httpMethod.releaseConnection(); } } return statusCode; }
From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.ConnectMgrVnfm.java
/** * Make connection//w w w . j ava 2s . co m * <br> * * @param vnfmObj * @return * @since NFVO 0.5 */ public int connect(JSONObject vnfmObj) { LOG.info("function=connect, msg=enter connect function."); ConnectInfo info = new ConnectInfo(vnfmObj.getString("url"), vnfmObj.getString("userName"), vnfmObj.getString("password"), Constant.ANONYMOUS); HttpMethod httpMethod = null; int statusCode = Constant.INTERNAL_EXCEPTION; try { httpMethod = new HttpRequests.Builder(info.getAuthenticateMode()) .setUrl(info.getUrl(), ParamConstants.CSM_AUTH_CONNECT) .setParams(String.format(ParamConstants.GET_TOKENS_V2, info.getUserName(), info.getUserPwd())) .post().execute(); statusCode = httpMethod.getStatusCode(); String result = httpMethod.getResponseBodyAsString(); if (statusCode == HttpStatus.SC_CREATED) { JSONObject accessObj = JSONObject.fromObject(result); JSONObject tokenObj = accessObj.getJSONObject("token"); Header header = httpMethod.getResponseHeader("accessSession"); setAccessSession(header.getValue()); setRoaRand(tokenObj.getString("roa_rand")); statusCode = HttpStatus.SC_OK; } else { LOG.error("connect fail, code:" + statusCode + " re:" + result); } } catch (JSONException e) { LOG.error("function=connect, msg=connect JSONException e={}.", e); } catch (VnfmException e) { LOG.error("function=connect, msg=connect VnfmException e={}.", e); } catch (IOException e) { LOG.error("function=connect, msg=connect IOException e={}.", e); } finally { clearCSMPwd(info); if (httpMethod != null) { httpMethod.releaseConnection(); } } return statusCode; }
From source file:org.openqa.selenium.remote.HttpCommandExecutor.java
public Response execute(Command command) throws Exception { CommandInfo info = nameToUrl.get(command.getName()); HttpMethod httpMethod = info.getMethod(remotePath, command); httpMethod.addRequestHeader("Accept", "application/json, image/png"); String payload = new BeanToJsonConverter().convert(command.getParameters()); if (httpMethod instanceof PostMethod) { ((PostMethod) httpMethod)/* w w w. j a v a 2 s . c o m*/ .setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8")); } client.executeMethod(httpMethod); // TODO: SimonStewart: 2008-04-25: This is really shabby if (isRedirect(httpMethod)) { Header newLocation = httpMethod.getResponseHeader("location"); httpMethod = new GetMethod(newLocation.getValue()); httpMethod.setFollowRedirects(true); httpMethod.addRequestHeader("Accept", "application/json, image/png"); client.executeMethod(httpMethod); } return createResponse(httpMethod); }