List of usage examples for org.apache.commons.httpclient HttpMethod setQueryString
public abstract void setQueryString(NameValuePair[] paramArrayOfNameValuePair);
From source file:org.olat.core.commons.modules.glossary.morphService.MorphologicalServiceDEImpl.java
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.isDebug()) { 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); }/*ww w .j ava 2 s . c o m*/ 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.isDebug()) { 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; }
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); }//from w ww .jav a 2 s.co m 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.user.propertyhandlers.ICQPropertyHandler.java
/** * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map) *///from w w w .j a va 2 s . co m @SuppressWarnings({ "unchecked", "unused" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; OLog log = Tracing.createLoggerFor(this.getClass()); if (StringHelper.containsNonWhitespace(textElement.getValue())) { // Use an HttpClient to fetch a profile information page from ICQ. final HttpClient httpClient = HttpClientFactory.getHttpClientInstance(); final HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setConnectionManagerTimeout(2500); httpClient.setParams(httpClientParams); final HttpMethod httpMethod = new GetMethod(ICQ_NAME_VALIDATION_URL); final NameValuePair uinParam = new NameValuePair(ICQ_NAME_URL_PARAMETER, textElement.getValue()); httpMethod.setQueryString(new NameValuePair[] { uinParam }); // Don't allow redirects since otherwise, we won't be able to get the HTTP 302 further down. 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 ICQ name exists. if (httpStatusCode == HttpStatus.SC_OK) { // ICQ tells us that a user name is valid if it sends an HTTP 200... result = true; } else if (httpStatusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // ...and if it's invalid, it sends an HTTP 302. textElement.setErrorKey("form.name.icq.error", null); result = false; } else { // For HTTP status codes other than 200 and 302 we will silently assume that the given ICQ name is valid, but inform the user about this. textElement.setExampleKey("form.example.icqname.notvalidated", null); log.warn("ICQ name validation: Expected HTTP status 200 or 301, but got " + httpStatusCode); result = true; } } catch (final Exception e) { // In case of any exception, assume that the given ICQ name is valid (The opposite would block easily upon network problems), and inform the user about // this. textElement.setExampleKey("form.example.icqname.notvalidated", null); log.warn("ICQ name validation: Exception: " + e.getMessage()); result = true; } } else { result = true; } log = null; return result; }
From source file:org.olat.user.propertyhandlers.MSNPropertyHandler.java
/** * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map) *//*w w w. j a va2 s . c o m*/ @SuppressWarnings({ "unchecked" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; OLog log = Tracing.createLoggerFor(this.getClass()); 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; } log = null; return result; }
From source file:org.openrdf.http.client.HTTPClient.java
public long size(Resource... contexts) throws IOException, RepositoryException, UnauthorizedException { checkRepositoryURL();/*w ww .j a v a2 s.c o m*/ String[] encodedContexts = Protocol.encodeContexts(contexts); NameValuePair[] contextParams = new NameValuePair[encodedContexts.length]; for (int i = 0; i < encodedContexts.length; i++) { contextParams[i] = new NameValuePair(Protocol.CONTEXT_PARAM_NAME, encodedContexts[i]); } HttpMethod method = new GetMethod(Protocol.getSizeLocation(repositoryURL)); setDoAuthentication(method); method.setQueryString(contextParams); try { int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_OK) { String response = method.getResponseBodyAsString(); try { return Long.parseLong(response); } catch (NumberFormatException e) { throw new RepositoryException("Server responded with invalid size value: " + response); } } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else { ErrorInfo errInfo = getErrorInfo(method); throw new RepositoryException(errInfo.toString()); } } finally { releaseConnection(method); } }
From source file:org.siberia.image.searcher.impl.GoogleImageSearcher.java
/** search */ public void search() { // http://images.google.fr/images?imgsz=xxlarge&gbv=2&hl=fr&q=b+e&btnG=Recherche+d%27images // http://images.google.fr/images?imgsz=xxlarge&hl=fr&q=b+e Runnable run = new Runnable() { public void run() { fireSearchHasBegan(new ImageSearcherEvent(GoogleImageSearcher.this)); StringBuffer buffer = new StringBuffer(50); if (getCriterions() != null) { boolean oneTokenAlreadyApplied = false; for (int i = 0; i < getCriterions().length; i++) { String current = getCriterions()[i]; if (current != null) { if (oneTokenAlreadyApplied) { buffer.append("+"); }//from w w w . java 2 s.co m buffer.append(current); oneTokenAlreadyApplied = true; } } } Locale locale = getLocale(); if (locale == null) { locale = Locale.getDefault(); } if (logger.isDebugEnabled()) { logger.debug("uri : " + buffer.toString()); } HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(GOOGLE_URL); NameValuePair[] pairs = new NameValuePair[3]; pairs[0] = new NameValuePair("imgsz", convertImageSizeCriterion(getImageSize())); pairs[1] = new NameValuePair("hl", locale.getCountry().toLowerCase()); pairs[2] = new NameValuePair("q", buffer.toString()); method.setQueryString(pairs); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); InputStream stream = null; try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { /** on recherche partir des motifs suivants * la premire occurrence de http:// partir de l, on prend jusqu'au prochaine espace ou '>' : * * exemple : * <img src=http://tbn0.google.com/images?q=tbn:GIJo-j_dSy4FiM:http://www.discogs.com/image/R-378796-1136999170.jpeg width=135 height=135> * * on trouve le motif, puis, on prend partir de http://www.discogs jusqu'au prochain espace... * * --> http://www.discogs.com/image/R-378796-1136999170.jpeg */ String searchMotif = "<img src=http://tbn0.google.com/images?q"; String urlMotif = "http://"; int indexInSearchMotif = -1; int indexInUrlMotif = -1; boolean motifFound = false; boolean foundUrl = false; StringBuffer urlBuffer = new StringBuffer(50); // Read the response body. byte[] bytes = new byte[1024 * 8]; stream = method.getResponseBodyAsStream(); if (stream != null) { int read = -1; int linksRetrieved = 0; while ((read = stream.read(bytes)) != -1) { for (int i = 0; i < read; i++) { byte currentByte = bytes[i]; if (motifFound) { if (foundUrl) { if (currentByte == ' ' || currentByte == '>') { /* add current url to list of result */ try { URL url = new URL(urlBuffer.toString()); fireImageFound(new ImageFoundEvent(GoogleImageSearcher.this, url, linksRetrieved)); linksRetrieved++; if (linksRetrieved >= getMaximumLinksRetrieved()) { break; } } catch (Exception e) { e.printStackTrace(); } finally { urlBuffer.delete(0, urlBuffer.length()); foundUrl = false; motifFound = false; } } else { /* add current byte to url buffer */ urlBuffer.append((char) currentByte); } } else { if (indexInUrlMotif == urlMotif.length() - 1) { urlBuffer.append(urlMotif); urlBuffer.append((char) currentByte); foundUrl = true; indexInUrlMotif = -1; } /* if the current byte is the same as that attempted on the url motif let's continue */ if (((char) currentByte) == urlMotif.charAt(indexInUrlMotif + 1)) { indexInUrlMotif++; } else { indexInUrlMotif = -1; } } } else { if (indexInSearchMotif == searchMotif.length() - 1) { motifFound = true; indexInSearchMotif = -1; } if (((char) currentByte) == searchMotif.charAt(indexInSearchMotif + 1)) { indexInSearchMotif++; } else { indexInSearchMotif = -1; } } } if (linksRetrieved >= getMaximumLinksRetrieved()) { break; } } } } else { System.err.println("Method failed: " + method.getStatusLine()); } } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { if (stream != null) { try { stream.close(); } catch (IOException ex) { System.err.println("Fatal transport error: " + ex.getMessage()); } } System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); fireSearchFinished(new ImageSearcherEvent(GoogleImageSearcher.this)); } } }; this.service.submit(run); }
From source file:org.soasecurity.wso2.mutual.auth.oauth2.client.MutualSSLOAuthClient.java
public static void main(String[] args) throws Exception { File file = new File((new File(".")).getCanonicalPath() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "keystore" + File.separator + keyStoreName); if (!file.exists()) { throw new Exception("Key Store file can not be found in " + file.getCanonicalPath()); }//from ww w . j ava2s.co m //Set trust store, you need to import server's certificate of CA certificate chain in to this //key store System.setProperty("javax.net.ssl.trustStore", file.getCanonicalPath()); System.setProperty("javax.net.ssl.trustStorePassword", keyStorePassword); //Set key store, this must contain the user private key //here we have use both trust store and key store as the same key store //But you can use a separate key store for key store an trust store. System.setProperty("javax.net.ssl.keyStore", file.getCanonicalPath()); System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword); HttpClient client = new HttpClient(); HttpMethod method = new PostMethod(endPoint); // Base64 encoded client id & secret method.setRequestHeader("Authorization", "Basic T09pN2dpUjUwdDZtUmU1ZkpmWUhVelhVa1QwYTpOOUI2dDZxQ0E2RFp2eTJPQkFIWDhjVlI1eUlh"); method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); NameValuePair pair1 = new NameValuePair(); pair1.setName("grant_type"); pair1.setValue("x509"); NameValuePair pair2 = new NameValuePair(); pair2.setName("username"); pair2.setValue("asela"); NameValuePair pair3 = new NameValuePair(); pair3.setName("password"); pair3.setValue("asela"); method.setQueryString(new NameValuePair[] { pair1, pair2, pair3 }); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("Failed: " + method.getStatusLine()); } else { byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); } }
From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java
/** * Execute method. In case of any exception thrown by HttpClient, it will release the connection. In other cases it * is the duty of caller to do it, or process the input stream. * //from w ww .j a v a 2s.c o m * @param method the method * @return the int */ protected int doExecuteMethod(ProxyRepository repository, ResourceStoreRequest request, HttpMethod method, URL remoteUrl) throws RemoteStorageException { URI methodURI = null; try { methodURI = method.getURI(); } catch (URIException e) { getLogger().debug("Could not format debug log message", e); } if (getLogger().isDebugEnabled()) { getLogger().debug("Invoking HTTP " + method.getName() + " method against remote location " + methodURI); } RemoteStorageContext ctx = getRemoteStorageContext(repository); HttpClient httpClient = (HttpClient) ctx.getContextObject(CTX_KEY_CLIENT); HostConfiguration httpConfiguration = (HostConfiguration) ctx.getContextObject(CTX_KEY_HTTP_CONFIGURATION); method.setRequestHeader(new Header("user-agent", formatUserAgentString(ctx, repository))); method.setRequestHeader(new Header("accept", "*/*")); method.setRequestHeader(new Header("accept-language", "en-us")); method.setRequestHeader(new Header("accept-encoding", "gzip, identity")); method.setRequestHeader(new Header("cache-control", "no-cache")); // HTTP keep alive should not be used, except when NTLM is used Boolean isNtlmUsed = (Boolean) ctx.getContextObject(HttpClientProxyUtil.NTLM_IS_IN_USE_KEY); if (isNtlmUsed == null || !isNtlmUsed) { method.setRequestHeader(new Header("Connection", "close")); method.setRequestHeader(new Header("Proxy-Connection", "close")); } method.setFollowRedirects(true); if (StringUtils.isNotBlank(ctx.getRemoteConnectionSettings().getQueryString())) { method.setQueryString(ctx.getRemoteConnectionSettings().getQueryString()); } int resultCode; try { resultCode = httpClient.executeMethod(httpConfiguration, method); final Header httpServerHeader = method.getResponseHeader("server"); checkForRemotePeerAmazonS3Storage(repository, httpServerHeader == null ? null : httpServerHeader.getValue()); Header proxyReturnedErrorHeader = method.getResponseHeader(NEXUS_MISSING_ARTIFACT_HEADER); boolean proxyReturnedError = proxyReturnedErrorHeader != null && Boolean.valueOf(proxyReturnedErrorHeader.getValue()); if (resultCode == HttpStatus.SC_FORBIDDEN) { throw new RemoteAccessDeniedException(repository, remoteUrl, HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN)); } else if (resultCode == HttpStatus.SC_UNAUTHORIZED) { throw new RemoteAuthenticationNeededException(repository, HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED)); } else if (resultCode == HttpStatus.SC_OK && proxyReturnedError) { throw new RemoteStorageException( "Invalid artifact found, most likely a proxy redirected to an HTML error page."); } } catch (RemoteStorageException e) { method.releaseConnection(); throw e; } catch (HttpException ex) { method.releaseConnection(); throw new RemoteStorageException("Protocol error while executing " + method.getName() + " method. [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex); } catch (IOException ex) { method.releaseConnection(); throw new RemoteStorageException("Transport error while executing " + method.getName() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + methodURI + "\"]", ex); } return resultCode; }
From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java
private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl) throws IOException { final String methodName = hsRequest.getMethod(); final HttpMethod method; if ("POST".equalsIgnoreCase(methodName)) { PostMethod postMethod = new PostMethod(); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity( hsRequest.getInputStream()); postMethod.setRequestEntity(inputStreamRequestEntity); method = postMethod;//from w w w . j a v a 2 s . c om } else if ("GET".equalsIgnoreCase(methodName)) { method = new GetMethod(); } else if ("PUT".equalsIgnoreCase(methodName)) { PutMethod putMethod = new PutMethod(); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity( hsRequest.getInputStream()); putMethod.setRequestEntity(inputStreamRequestEntity); method = putMethod; } else if ("DELETE".equalsIgnoreCase(methodName)) { method = new DeleteMethod(); } else { log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod()); return null; } method.setFollowRedirects(false); method.setPath(targetUrl.getPath()); method.setQueryString(targetUrl.getQuery()); Enumeration e = hsRequest.getHeaderNames(); if (e != null) { while (e.hasMoreElements()) { String headerName = (String) e.nextElement(); if ("host".equalsIgnoreCase(headerName)) { //the host value is set by the http client continue; } else if ("content-length".equalsIgnoreCase(headerName)) { //the content-length is managed by the http client continue; } else if ("accept-encoding".equalsIgnoreCase(headerName)) { //the accepted encoding should only be those accepted by the http client. //The response stream should (afaik) be deflated. If our http client does not support //gzip then the response can not be unzipped and is delivered wrong. continue; } else if (headerName.toLowerCase().startsWith("cookie")) { //fixme : don't set any cookies in the proxied request, this needs a cleaner solution continue; } Enumeration values = hsRequest.getHeaders(headerName); while (values.hasMoreElements()) { String headerValue = (String) values.nextElement(); log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue); method.addRequestHeader(headerName, headerValue); } } } if (log.isInfoEnabled()) log.info("proxy query string " + method.getQueryString()); return method; }
From source file:org.tuleap.mylyn.task.core.internal.client.rest.RestOperation.java
/** * Provides the Method to run.//from w w w. j ava 2s . c o m * * @return The method to run. */ public HttpMethod createMethod() { HttpMethod m = method.create(); if (m instanceof EntityEnclosingMethod) { StringRequestEntity entity; try { if (body == null) { entity = new StringRequestEntity(EMPTY_BODY, CONTENT_TYPE_JSON, ENCODING_UTF8); } else { entity = new StringRequestEntity(body, CONTENT_TYPE_JSON, ENCODING_UTF8); } } catch (UnsupportedEncodingException e) { logger.log(new Status(IStatus.ERROR, TuleapCoreActivator.PLUGIN_ID, TuleapCoreMessages.getString(TuleapCoreKeys.encodingUtf8NotSupported))); return null; } ((EntityEnclosingMethod) m).setRequestEntity(entity); } m.setPath(fullUrl); for (Entry<String, String> entry : requestHeaders.entrySet()) { m.addRequestHeader(entry.getKey(), entry.getValue()); } NameValuePair[] queryParams = new NameValuePair[requestParameters.size()]; int i = 0; for (Entry<String, String> entry : requestParameters.entries()) { queryParams[i++] = new NameValuePair(entry.getKey(), entry.getValue()); } m.setQueryString(queryParams); return m; }