Example usage for org.apache.commons.httpclient HttpMethod setQueryString

List of usage examples for org.apache.commons.httpclient HttpMethod setQueryString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setQueryString.

Prototype

public abstract void setQueryString(NameValuePair[] paramArrayOfNameValuePair);

Source Link

Usage

From source file:gov.loc.ndmso.proxyfilter.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  av  a  2 s.c  om
    } else if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod();
    } else {
        // log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod());
        return null;
    }

    method.setFollowRedirects(false);
    method.setPath(targetUrl.getPath());
    method.setQueryString(targetUrl.getQuery());

    @SuppressWarnings("unchecked")
    Enumeration<String> e = hsRequest.getHeaderNames();
    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = 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;
            }

            @SuppressWarnings("unchecked")
            Enumeration<String> values = hsRequest.getHeaders(headerName);
            while (values.hasMoreElements()) {
                String headerValue = values.nextElement();
                // log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue);
                method.addRequestHeader(headerName, headerValue);
            }
        }
    }

    // add rs5/tomcat5 request header for ML
    method.addRequestHeader("X-Via", "tomcat5");

    // log.info("proxy query string " + method.getQueryString());
    return method;
}

From source file:net.oauth.client.OAuthHttpClient.java

/** Send a message to the service provider and get the response. */
@Override//from ww w. j av  a 2  s  .  co  m
protected OAuthMessage invoke(OAuthMessage message) throws Exception {
    String form = OAuth.formEncode(message.getParameters());
    HttpMethod method;
    if ("GET".equals(message.httpMethod)) {
        method = new GetMethod(message.URL);
        method.setQueryString(form);
        // method.addRequestHeader("Authorization", message
        // .getAuthorizationHeader(serviceProvider.userAuthorizationURL));
        method.setFollowRedirects(false);
    } else {
        PostMethod post = new PostMethod(message.URL);
        post.setRequestEntity(new StringRequestEntity(form, OAuth.FORM_ENCODED, null));
        method = post;
    }
    clientPool.getHttpClient(new URL(method.getURI().toString())).executeMethod(method);
    final OAuthMessage response = new HttpMethodResponse(method);
    int statusCode = method.getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        Map<String, Object> dump = response.getDump();
        OAuthProblemException problem = new OAuthProblemException(
                (String) dump.get(OAuthProblemException.OAUTH_PROBLEM));
        problem.getParameters().putAll(dump);
        throw problem;
    }
    return response;
}

From source file:com.intellij.plugins.firstspirit.languagesupport.FirstSpiritClassPathHack.java

public void addFirstSpiritClientJar(UrlClassLoader classLoader, HttpScheme schema, String serverName, int port,
        String firstSpiritUserName, String firstSpiritUserPassword) throws Exception {
    System.out.println("starting to download fs-client.jar");

    String resolvalbleAddress = null;

    // asking DNS for IP Address, if some error occur choose the given value from user
    try {/* w w  w .  j av a 2 s.  c  om*/
        InetAddress address = InetAddress.getByName(serverName);
        resolvalbleAddress = address.getHostAddress();
        System.out.println("Resolved address: " + resolvalbleAddress);
    } catch (Exception e) {
        System.err.println("DNS cannot resolve address, using your given value: " + serverName);
        resolvalbleAddress = serverName;
    }

    String uri = schema + "://" + resolvalbleAddress + ":" + port + "/clientjar/fs-client.jar";
    String versionUri = schema + "://" + resolvalbleAddress + ":" + port + "/version.txt";
    String tempDirectory = System.getProperty("java.io.tmpdir");

    System.out.println(uri);
    System.out.println(versionUri);

    HttpClient client = new HttpClient();
    HttpMethod getVersion = new GetMethod(versionUri);
    client.executeMethod(getVersion);
    String currentServerVersionString = getVersion.getResponseBodyAsString();
    System.out
            .println("FirstSpirit server you want to connect to is at version: " + currentServerVersionString);

    File fsClientJar = new File(tempDirectory, "fs-client-" + currentServerVersionString + ".jar");

    if (!fsClientJar.exists()) {
        // get an authentication cookie from FirstSpirit
        HttpMethod post = new PostMethod(uri);
        post.setQueryString("login.user=" + URLEncoder.encode(firstSpiritUserName, "UTF-8") + "&login.password="
                + URLEncoder.encode(firstSpiritUserPassword, "UTF-8") + "&login=webnonsso");
        client.executeMethod(post);
        String setCookieJsession = post.getResponseHeader("Set-Cookie").getValue();

        // download the fs-client.jar by using the authentication cookie
        HttpMethod get = new GetMethod(uri);
        get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        get.setRequestHeader("Cookie", setCookieJsession);
        client.executeMethod(get);

        InputStream inputStream = get.getResponseBodyAsStream();
        FileOutputStream outputStream = new FileOutputStream(fsClientJar);
        outputStream.write(IOUtils.readFully(inputStream, -1, false));
        outputStream.close();
        System.out.println("tempfile of fs-client.jar created within path: " + fsClientJar);
    }

    addFile(classLoader, fsClientJar);
}

From source file:com.ikon.util.MailUtils.java

/**
 * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of
 * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4
 *//*from ww w.jav a 2s.c  o  m*/
public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
    HttpClient httpclient = new HttpClient();

    // Prepare a request object
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] { new NameValuePair("url", fullUrl) });
    httpclient.executeMethod(method);
    InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
    StringWriter sw = new StringWriter();
    int c;
    while ((c = isr.read()) != -1)
        sw.write(c);
    isr.close();
    method.releaseConnection();

    return sw.toString();
}

From source file:net.datapipe.CloudStack.CloudStackAPI.java

protected HttpMethod makeHttpGet(LinkedList<NameValuePair> queryValues) throws Exception {
    String query_signature = sign_request(queryValues);
    queryValues.add(new NameValuePair("signature", query_signature));

    HttpMethod method = new GetMethod(apiURL);
    method.setFollowRedirects(true);//from   w  ww  .  j ava 2  s  .  c om
    method.setQueryString(queryValues.toArray(new NameValuePair[0]));

    return method;
}

From source file:com.sun.syndication.feed.weather.WeatherGateway.java

protected WeatherChannel doQuery(String locationID, long allowedAge, NameValuePair[] query) throws IOException {
    HttpClient client = new HttpClient();

    HttpMethod method = new GetMethod(weatherServer + locationID);
    method.setQueryString(query);

    URI uri = method.getURI();//from w  w w .  j  ava2  s.c  om
    LOG.debug("Performing query with URI:  " + uri);

    WeatherChannel channel = new WeatherChannel();

    if (weatherCache.containsKey(uri)) {
        WeatherCacheEntry entry = (WeatherCacheEntry) weatherCache.get(uri);

        long lastUpdated = entry.getLastUpdated().getTimeInMillis();
        LOG.debug("Cache entry last updated:  " + lastUpdated);
        long now = new GregorianCalendar().getTimeInMillis();
        LOG.debug("Cache entry current time:  " + now);
        long diffMillis = now - lastUpdated;
        LOG.debug("Cache entry time difference is:  " + diffMillis);

        if (diffMillis < allowedAge) {
            channel = entry.getChannel();
            LOG.debug("Returning channel from cache.");
            return channel;
        }
    }

    int statusCode = -1;

    for (int attempt = 0; statusCode == -1 && attempt < 3; attempt++) {
        try {
            statusCode = client.executeMethod(method);
        } catch (HttpRecoverableException e) {
            LOG.warn("Retrying after recoverable exception:  " + e.getMessage());
        } catch (IOException e) {
            LOG.error("Failed to download file:  " + e.getMessage());
        }
    }

    if (statusCode == -1) {
        LOG.error("Failed to recover from exception.");
        throw new IOException();
    }

    channel = buildWeather(method);
    WeatherCacheEntry entry = new WeatherCacheEntry(channel);
    weatherCache.put(uri, entry);
    LOG.debug("Returning channel from network.");
    return channel;
}

From source file:com.ideabase.repository.webservice.client.impl.HttpWebServiceControllerImpl.java

private HttpMethod prepareMethod(final String pMethod, final String pServiceUri,
        final NameValuePair[] pParameters) {
    LOG.debug("Prepare appropriate http method.");

    final String baseUrl;
    if (mBaseUrl.endsWith("/")) {
        baseUrl = mBaseUrl.substring(0, mBaseUrl.length() - 1);
    } else {//from  w w w . jav a  2  s  .  c  om
        baseUrl = mBaseUrl;
    }
    final String fullQualifiedUri = baseUrl + pServiceUri;
    final HttpMethod httpMethod;
    // GET method
    if (GET.equalsIgnoreCase(pMethod)) {
        httpMethod = new GetMethod(fullQualifiedUri);
        if (pParameters != null) {
            httpMethod.setQueryString(pParameters);
        }
    }
    // POST method
    else if (POST.equalsIgnoreCase(pMethod)) {
        httpMethod = new PostMethod(fullQualifiedUri);
        if (pParameters != null) {
            ((PostMethod) httpMethod).addParameters(pParameters);
        }
    }
    // DELETE method
    else if (DELETE.equalsIgnoreCase(pMethod)) {
        httpMethod = new DeleteMethod(fullQualifiedUri);
        if (pParameters != null) {
            httpMethod.setQueryString(pParameters);
        }
    }
    // If no such known method.
    else {
        throw new UnsupportedOperationException("Unknown method type - " + pMethod);
    }
    return httpMethod;
}

From source file:com.thoughtworks.go.helpers.HttpClientHelper.java

private HttpMethod doRequest(String path, RequestMethod methodRequired, String params) throws IOException {
    HttpMethod method = null;
    String url = baseUrl + path;/*w ww.j a  va2  s .c om*/
    switch (methodRequired) {
    case PUT:
        method = new PutMethod(url);
        break;
    case POST:
        method = new PostMethod(url);
        break;
    case GET:
        method = new GetMethod(url);
        break;
    }
    method.setQueryString(params);
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    return method;
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.services.SettingsLoaderImpl.java

private void configureMethod(HttpMethod method, String eid, String sessionId, String csrfNonce) {
    method.setFollowRedirects(false);// ww w.j  a  v  a2  s.  co  m
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionId);
    method.setQueryString(new NameValuePair[] { new NameValuePair("eid", eid),
            new NameValuePair(REQUEST_PARAMETER_CSRF_NONCE, csrfNonce) });
}

From source file:com.zimbra.qa.unittest.TestPreAuthServlet.java

public void testShouldNotAllowPreAuthGetCookieReuse() throws Exception {
    Account account = TestUtil.getAccount("user1");
    AuthToken authToken = new ZimbraAuthToken(account);
    System.out.println(authToken.isRegistered());
    HttpClient client = new HttpClient();
    Server localServer = Provisioning.getInstance().getLocalServer();
    String protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);
    String url = protoHostPort + PRE_AUTH_URL;

    //allow first request
    HttpMethod method = new GetMethod(url);
    NameValuePair[] queryStringPairArray = new NameValuePair[] { new NameValuePair("isredirect", "1"),
            new NameValuePair("authtoken", authToken.getEncoded()) };
    method.setQueryString(queryStringPairArray);
    int respCode = HttpClientUtil.executeMethod(client, method);

    //reject second request
    method = new GetMethod(url);
    method.setQueryString(queryStringPairArray);
    respCode = HttpClientUtil.executeMethod(client, method);
    Assert.assertEquals(400, respCode);/*from w  w w .j  a v a 2s.  com*/
}