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

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

Introduction

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

Prototype

public abstract String getQueryString();

Source Link

Usage

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequestTestCase.java

public void testPutMethod() throws Exception {
    final MuleMessage message = setupRequestContext("http://localhost:8080/services", HttpConstants.METHOD_PUT);
    final String contentType = "text/plain";

    message.setPayload("I'm a payload");
    message.setInvocationProperty(HttpConstants.HEADER_CONTENT_TYPE, contentType);

    final ObjectToHttpClientMethodRequest transformer = createTransformer();
    final Object response = transformer.transform(message);

    assertTrue(response instanceof PutMethod);
    final HttpMethod httpMethod = (HttpMethod) response;
    assertEquals(null, httpMethod.getQueryString());

    assertEquals(contentType, httpMethod.getRequestHeader(HttpConstants.HEADER_CONTENT_TYPE).getValue());
}

From source file:org.pentaho.di.baserver.utils.web.HttpConnectionHelperTest.java

@Test
public void testGetHttpMethod() throws Exception {
    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put("param1", "value1");
    queryParameters.put("param2", "value2");
    queryParameters.put("param3", "value3");
    String url = "http://localhost:8080/pentaho";

    HttpMethod method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "GET");
    assertEquals(method.getClass(), GetMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    assertNotNull(method.getQueryString());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "PUT");
    assertEquals(method.getClass(), PutMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    RequestEntity requestEntity = ((PutMethod) method).getRequestEntity();
    assertNotNull(requestEntity);/*  ww w.  j av  a  2 s . c  o m*/
    assertEquals(requestEntity.getContentType(), "application/x-www-form-urlencoded; charset=UTF-8");
    assertNull(method.getQueryString());
    assertEquals(requestEntity.getClass(), StringRequestEntity.class);
    assertNotNull(((StringRequestEntity) requestEntity).getContent());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "POST");
    assertEquals(method.getClass(), PostMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    requestEntity = ((PostMethod) method).getRequestEntity();
    assertNotNull(requestEntity);
    assertEquals(requestEntity.getContentType(), "application/x-www-form-urlencoded; charset=UTF-8");
    assertNull(method.getQueryString());
    assertEquals(requestEntity.getClass(), StringRequestEntity.class);
    assertNotNull(((StringRequestEntity) requestEntity).getContent());

    // POST without parameters
    method = httpConnectionHelperSpy.getHttpMethod(url, null, "POST");
    assertEquals(method.getClass(), PostMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    requestEntity = ((PostMethod) method).getRequestEntity();
    assertNotNull(requestEntity);
    assertEquals(requestEntity.getContentType(), "application/x-www-form-urlencoded; charset=UTF-8");
    assertNull(method.getQueryString());
    assertEquals(requestEntity.getClass(), StringRequestEntity.class);
    assertNotNull(((StringRequestEntity) requestEntity).getContent());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "DELETE");
    assertEquals(method.getClass(), DeleteMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    assertNotNull(method.getQueryString());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "HEAD");
    assertEquals(method.getClass(), HeadMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    assertNotNull(method.getQueryString());

    method = httpConnectionHelperSpy.getHttpMethod(url, queryParameters, "OPTIONS");
    assertEquals(method.getClass(), OptionsMethod.class);
    assertTrue(method.getURI().toString().startsWith(url));
    assertNotNull(method.getQueryString());
}

From source file:org.tgta.tagger.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;//from   w  ww.ja  v  a2s  . c om

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        //byte[] responseBody;
        InputStream in = method.getResponseBodyAsStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
        }
        //System.out.println(out.toString());   //Prints the string content read from input stream
        reader.close();

        response = out.toString();

        //TODO Going to buffer response body of large or unknown size. 
        //Using getResponseBodyAsStream instead is recommended.

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        //response = new String(responseBody);

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

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;//  ww w. j av a2s  . 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.TuleapRestConnector.java

/**
 * Logs a debug message of the REST request/response.
 *
 * @param method// w  ww.  j  a v  a  2  s.c  o m
 *            The method executed
 * @param bodyReceived
 *            The response body received
 */
private void debugRestCall(HttpMethod method, String bodyReceived) {
    int responseStatus = method.getStatusCode();
    StringBuilder b = new StringBuilder();
    b.append(method.getName());
    b.append(" ").append(method.getPath()); //$NON-NLS-1$
    String qs = method.getQueryString();
    if (qs != null && !qs.isEmpty()) {
        b.append('?').append(method.getQueryString());
    }
    if (method instanceof EntityEnclosingMethod) {
        RequestEntity requestEntity = ((EntityEnclosingMethod) method).getRequestEntity();
        String body = ""; //$NON-NLS-1$
        if (requestEntity.isRepeatable()) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                requestEntity.writeRequest(os);
                body = os.toString("UTF-8"); //$NON-NLS-1$
            } catch (UnsupportedEncodingException e) {
                // Nothing to do
            } catch (IOException e) {
                // Nothing to do
            }
        }
        b.append("\nbody:\n").append(body.replaceAll(//$NON-NLS-1$
                "\"password\" *: *\".*\"", "\"password\":\"(hidden in debug)\"")); //$NON-NLS-1$ //$NON-NLS-2$
    }
    b.append("\n__________\nresponse:\n"); //$NON-NLS-1$
    b.append(method.getStatusLine()).append("\n"); //$NON-NLS-1$
    b.append("body:\n"); //$NON-NLS-1$
    b.append(bodyReceived);
    int status = IStatus.INFO;
    if (responseStatus != HttpURLConnection.HTTP_OK) {
        status = IStatus.ERROR;
    }
    this.logger.log(new Status(status, TuleapCoreActivator.PLUGIN_ID, b.toString()));
}

From source file:org.tuleap.mylyn.task.core.tests.internal.client.rest.MockPaginatingRestConnector.java

@Override
public ServerResponse sendRequest(HttpMethod method) {
    String queryString = method.getQueryString();
    String[] strings = queryString.split("&"); //$NON-NLS-1$
    for (String s : strings) {
        if (s.startsWith("offset=")) { //$NON-NLS-1$
            String offset = s.substring("offset=".length()).trim(); //$NON-NLS-1$
            invocationsCount++;//from w w w.  j ava  2s .  co m
            return responses.get(offset);
        }
    }
    return super.sendRequest(method);
}

From source file:org.tuleap.mylyn.task.core.tests.internal.client.rest.MockRestConnector.java

protected ServerRequest getServerRequest(HttpMethod method) {
    Map<String, String> header = new LinkedHashMap<String, String>();
    for (Header h : method.getRequestHeaders()) {
        header.put(h.getName(), h.getValue());
    }/*from   ww w  .ja va 2  s  .  c o  m*/
    if (method instanceof EntityEnclosingMethod) {
        RequestEntity entity = ((EntityEnclosingMethod) method).getRequestEntity();
        if (entity instanceof StringRequestEntity) {
            return new ServerRequest(method.getName(), method.getPath(), header, method.getQueryString(),
                    ((StringRequestEntity) entity).getContent());
        }
    }
    return new ServerRequest(method.getName(), method.getPath(), header, method.getQueryString());
}

From source file:org.tuleap.mylyn.task.core.tests.internal.client.rest.RestOperationsTest.java

@Test
public void testBasicBehavior() {
    RestOperation op = RestOperation.get("some/url", connector, gson, logger);
    HttpMethod m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("", m.getQueryString());

    op.withQueryParameter("key1", "value1");
    m = op.createMethod();/*  w ww . jav a2s . c  o  m*/
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key1=value1", m.getQueryString());

    op.withQueryParameter("key1", "value1b");
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key1=value1b", m.getQueryString());

    op.withQueryParameter("key1", "value1", "value1b");
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key1=value1&key1=value1b", m.getQueryString());

    op.withQueryParameter("key2", "value2");
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key1=value1&key1=value1b&key2=value2", m.getQueryString());

    op.withoutQueryParameters("key1");
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("key2=value2", m.getQueryString());

    op.withoutQueryParameter();
    m = op.createMethod();
    assertEquals("GET", m.getName());
    assertEquals("some/url", m.getPath());
    assertEquals("", m.getQueryString());
}

From source file:org.tuleap.mylyn.task.core.tests.internal.client.rest.RestResourceTest.java

/**
 * Test the pagination on GET with HEADER_X_PAGINATION_SIZE not set.
 * /*from   w  w w.  java  2 s . co m*/
 * @throws CoreException
 *             The exception to throw
 */
@Test
public void testGetPaginationSizeNotSet() throws CoreException {
    RestResource r = new RestResource("/server/api/v12.5/my/url", RestResource.GET, connector, gson,
            new TestLogger());
    Map<String, String> headers = Maps.newTreeMap();
    headers.put(RestResource.ALLOW, "OPTIONS,GET");
    headers.put(RestResource.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS,GET");
    connector.setResponse(new ServerResponse(ServerResponse.STATUS_OK, "", headers));
    RestOperation get = r.get();
    HttpMethod method = get.createMethod();
    assertEquals("GET", method.getName());
    assertEquals("/server/api/v12.5/my/url", method.getPath());
    assertEquals("", method.getQueryString());

    headers.put(RestResource.HEADER_X_PAGINATION_LIMIT_MAX, "10");
    connector.setResponse(new ServerResponse(ServerResponse.STATUS_OK, "", headers));
    get = r.get();
    method = get.createMethod();
    assertEquals("GET", method.getName());
    assertEquals("/server/api/v12.5/my/url", method.getPath());
    assertEquals("", method.getQueryString());
}

From source file:org.wingsource.plugin.impl.gadget.bean.Gadget.java

private Response getResponse(String tokenId, String href, Map<String, String> requestParameters) {
    logger.finest("Fetching content using HttpClient....user-Id: " + tokenId);
    HttpClient hc = new HttpClient();
    hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    HttpMethod method = new GetMethod(href);
    method.addRequestHeader("xx-wings-user-id", tokenId);
    ArrayList<NameValuePair> nvpList = new ArrayList<NameValuePair>();
    Set<String> keys = requestParameters.keySet();
    for (String key : keys) {
        String value = requestParameters.get(key);
        nvpList.add(new NameValuePair(key, value));
    }/*ww  w  . j  av a2  s  .  c  o  m*/

    String qs = method.getQueryString();
    if (qs != null) {
        String[] nvPairs = qs.split("&");
        for (String nvPair : nvPairs) {
            String[] mapping = nvPair.split("=");
            nvpList.add(new NameValuePair(mapping[0], mapping[1]));
        }
    }
    method.setFollowRedirects(true);

    NameValuePair[] nvps = new NameValuePair[nvpList.size()];
    nvps = nvpList.toArray(nvps);
    method.setQueryString(nvps);

    byte[] content = null;
    Header[] headers = null;
    try {
        hc.executeMethod(method);
        content = method.getResponseBody();
        headers = method.getResponseHeaders();
    } catch (HttpException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
    return new Response(content, headers);
}