Example usage for org.apache.http.client.utils URLEncodedUtils parse

List of usage examples for org.apache.http.client.utils URLEncodedUtils parse

Introduction

In this page you can find the example usage for org.apache.http.client.utils URLEncodedUtils parse.

Prototype

public static List<NameValuePair> parse(final String s, final Charset charset) 

Source Link

Document

Returns a list of NameValuePair NameValuePairs as parsed from the given string using the given character encoding.

Usage

From source file:org.asimba.wa.integrationtest.authmethod.IdentifyingAuthnMethodIntegrationTest.java

private HtmlPage navigateToIdentifyingForm(SAML2SP samlClient, WebClient webClient) throws Exception {
    // Make the AuthnRequest
    String content;//from  www. j  a va 2  s .  c o  m
    WebRequest webRequest = samlClient.getAuthnWebRequest(_samlWebSSOUrl,
            SAMLConstants.SAML2_REDIRECT_BINDING_URI);
    _logger.debug("Sending (httpclient) request to {}", webRequest.getUrl().toString());

    HtmlPage htmlPage = _webClient.getPage(webRequest);
    content = htmlPage.asXml();
    _logger.debug("Received (1): {}", content);

    // Make assertions about the response:
    // -- one of the items has a link that has "profile=local.identifying" in querystring
    HtmlAnchor theAnchor = null;
    // alternative to:
    //   List<?> list = htmlPage.getByXPath(
    //      "/html/body/div[@id='container']/div[@id='content']/div[@id='contentMain']/form[@id='selectionForm']/fieldset/ul/li/a");
    List<HtmlAnchor> anchors = htmlPage.getAnchors();
    theanchorloop: for (HtmlAnchor anchor : anchors) {
        String href = anchor.getHrefAttribute();
        List<NameValuePair> params = URLEncodedUtils.parse(new URI(href), "UTF-8");
        for (NameValuePair nvp : params) {
            if ("profile".equals(nvp.getName())) {
                if ("local.identifying".equals(nvp.getValue())) {
                    theAnchor = anchor;
                    break theanchorloop;
                }
            }
        }
    }

    _logger.info("Found anchor: {}", theAnchor);
    assertNotNull(theAnchor);

    // Click the identifying method -- should result in HTML page with form to enter username
    htmlPage = theAnchor.click();

    content = htmlPage.asXml();
    _logger.debug("Received (2): {}", content);

    return htmlPage;
}

From source file:com.kolich.aws.services.s3.impl.KolichS3Signer.java

/**
  * Calculate the canonical string for a REST/HTTP request to S3.
  *///from  ww  w . j  ava  2 s  . c o m
private static final String getS3CanonicalString(final AwsHttpRequest request) {
    // A few standard headers we extract for conveinence.
    final String contentType = CONTENT_TYPE.toLowerCase(), contentMd5 = CONTENT_MD5.toLowerCase(),
            date = DATE.toLowerCase();
    // Start with the empty string ("").
    final StringBuilder buf = new StringBuilder();
    // Next is the HTTP verb and a newline.
    buf.append(request.getMethod() + LINE_SEPARATOR_UNIX);
    // Add all interesting headers to a list, then sort them.
    // "Interesting" is defined as Content-MD5, Content-Type, Date,
    // and x-amz-... headers.
    final Map<String, String> headersMap = getHeadersAsMap(request);
    final SortedMap<String, String> interesting = Maps.newTreeMap();
    if (!headersMap.isEmpty()) {
        Iterator<Map.Entry<String, String>> it = headersMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            final String key = entry.getKey(), value = entry.getValue();
            if (key == null) {
                continue;
            }
            final String lk = key.toLowerCase(Locale.getDefault());
            // Ignore any headers that are not interesting.
            if (lk.equals(contentType) || lk.equals(contentMd5) || lk.equals(date)
                    || lk.startsWith(AMAZON_PREFIX)) {
                interesting.put(lk, value);
            }
        }
    }
    // Remove default date timestamp if "x-amz-date" is set.
    if (interesting.containsKey(S3_ALTERNATE_DATE)) {
        interesting.put(date, "");
    }
    // These headers require that we still put a new line in after them,
    // even if they don't exist.
    if (!interesting.containsKey(contentType)) {
        interesting.put(contentType, "");
    }
    if (!interesting.containsKey(contentMd5)) {
        interesting.put(contentMd5, "");
    }
    // Add all the interesting headers
    for (Iterator<Map.Entry<String, String>> i = interesting.entrySet().iterator(); i.hasNext();) {
        final Map.Entry<String, String> entry = i.next();
        final String key = entry.getKey();
        final Object value = entry.getValue();
        if (key.startsWith(AMAZON_PREFIX)) {
            buf.append(key).append(':').append(value);
        } else {
            buf.append(value);
        }
        buf.append(LINE_SEPARATOR_UNIX);
    }
    // The CanonicalizedResource this request is working with.
    // If the request specifies a bucket using the HTTP Host header
    // (virtual hosted-style), append the bucket name preceded by a
    // "/" (e.g., "/bucketname"). For path-style requests and requests
    // that don't address a bucket, do nothing.
    if (request.getResource() != null) {
        buf.append("/" + request.getResource() + request.getURI().getRawPath());
    } else {
        buf.append(request.getURI().getRawPath());
    }
    // Amazon requires us to sort the query string parameters.
    final List<SortableBasicNameValuePair> params = sortParams(URLEncodedUtils.parse(request.getURI(), UTF_8));
    String separator = "?";
    for (final NameValuePair pair : params) {
        final String name = pair.getName(), value = pair.getValue();
        // Skip any parameters that aren't part of the
        // canonical signed string.
        if (!INTERESTING_PARAMETERS.contains(name)) {
            continue;
        }
        buf.append(separator).append(name);
        if (value != null) {
            buf.append("=").append(value);
        }
        separator = "&";
    }
    return buf.toString();
}

From source file:com.stratio.morphlines.refererparser.Parser.java

private Map<String, String> buildParamsMap(String query) {
    List<NameValuePair> params = null;
    try {/*ww  w  .ja  v  a2 s .  c  o m*/
        params = URLEncodedUtils.parse(new URI(HTTP_LOCALHOST + query), "UTF-8");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    Map<String, String> paramsMap = new HashMap<String, String>();
    for (NameValuePair param : params) {
        paramsMap.put(param.getName(), param.getValue());

    }
    return paramsMap;
}

From source file:com.smartling.api.sdk.FileApiClientAdapterTest.java

@Test
public void testFileGetList() throws ApiException, IOException {
    String uriMask = "URI_MASK";
    Date lastUploadedAfter = new Date();
    Date lastUploadedBefore = new Date();

    FileListSearchParams fileListSearchParams = getFileListSearchParams(uriMask, lastUploadedAfter,
            lastUploadedBefore);//from www  .  j a v a  2s. c om

    when(response.getContents()).thenReturn(FILE_LIST_RESPONSE);

    ApiResponse<FileList> apiResponse = fileApiClientAdapter.getFilesList(fileListSearchParams);

    // Validate the request
    HttpRequestBase request = requestCaptor.getValue();
    List<NameValuePair> params = URLEncodedUtils.parse(request.getURI(), "UTF-8");
    assertFileListRequestParams(lastUploadedAfter, lastUploadedBefore, params);
    assertEquals(HOST, request.getURI().getHost());

    // Validate the response
    FileList fileList = apiResponse.getData();
    assertFileList(fileList);
}

From source file:org.ovirt.engine.sdk4.internal.HttpConnection.java

/**
 * Injects HTTP headers in to request/*w w w . j  a  v a 2s .  co  m*/
 *
 * @param request
 */
private void injectHeaders(HttpUriRequest request) {
    List<Header> updated = excludeNullHeaders(request.getAllHeaders());
    if (updated != null && !updated.isEmpty()) {
        request.setHeaders(updated.toArray(new Header[updated.size()]));
    }

    for (NameValuePair nameValuePair : URLEncodedUtils.parse(request.getURI(), HTTP.UTF_8)) {
        if (nameValuePair.getName().equalsIgnoreCase("all_content")) {
            request.addHeader("All-Content", nameValuePair.getValue());
        }
    }

    request.addHeader("Version", "4");
    request.addHeader("Content-type", "application/xml");
    request.addHeader("User-Agent", "JavaSDK");
    request.addHeader("Accept", "application/xml");
    request.addHeader("Authorization", "Bearer " + getAccessToken());
}

From source file:io.stallion.requests.StRequest.java

@Override
public Map<String, Object> getBodyMap() {
    if (bodyMap == null) {
        if (or(getHeader("Content-type"), "").startsWith("application/x-www-form-urlencoded")) {
            bodyMap = new HashMap<>();

            for (NameValuePair pair : URLEncodedUtils.parse(getContent(),
                    Charset.forName(or(request.getCharacterEncoding(), "UTF8")))) {
                if (bodyMap.containsKey(pair.getName())) {
                    Object existing = bodyMap.get(pair.getName());
                    if (existing instanceof List) {
                        ((List) existing).add(pair.getValue());
                    } else {
                        bodyMap.put(pair.getName(), list(existing, pair.getValue()));
                    }/*  w ww  .j  a v a  2  s  . c o  m*/
                } else {
                    bodyMap.put(pair.getName(), pair.getValue());
                }
            }
        } else {
            ObjectMapper mapper = new ObjectMapper();
            String content = getContent();
            if (StringUtils.isEmpty(content)) {
                bodyMap = new HashMap<>();
            } else {
                try {
                    bodyMap = mapper.readValue(getContent(), new TypeReference<HashMap<String, Object>>() {
                    });
                } catch (IOException e) {
                    Log.exception(e, "Could not parse JSON body for the request: " + content);
                    throw new ClientException("Could not parse JSON body for the request.");
                }

            }
        }
    }
    return bodyMap;
}

From source file:nl.uva.mediamosa.MediaMosaConnector.java

public String doPostRequest(String postRequest, String postParams) throws IOException {
    String content = null;//from   www .j  av a  2 s  .co m
    HttpPost httppost = new HttpPost(host + postRequest);
    List<NameValuePair> nvps = URLEncodedUtils.parse(postParams, Charset.forName("UTF-8"));
    httppost.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName("UTF-8")));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    InputStream is = null;
    try {
        if (entity != null) {
            is = entity.getContent();
            content = IOUtils.toString(is);
            this.responseHeader = XmlParserUtil.parseResponse(content);
        }
    } finally {
        if (is != null) {
            is.close();
        }
    }

    // if cookie is expired, then relogin
    if (responseHeader.getRequestResultId() == ErrorCodes.ERRORCODE_ACCES_DENIED) {
        doLogin();
        doPostRequest(postRequest, postParams);
    }
    return content;
}

From source file:nl.uva.mediamosa.impl.MediaMosaImpl.java

/**
 * @param postRequest//from  www . java  2 s  .co m
 * @param postParams
 * @return
 * @throws java.io.IOException
 */
public Response doPostRequest(String uploadHost, String postRequest, String postParams, InputStream stream,
        String mimeType, String filename) throws IOException {
    HttpPost httpPost = new HttpPost(uploadHost + postRequest);

    MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
    mpBuilder.addBinaryBody("file", stream, ContentType.create(mimeType), filename);

    List<NameValuePair> nvps = URLEncodedUtils.parse(postParams, Charset.forName("UTF-8"));
    for (NameValuePair nameValuePair : nvps) {
        mpBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
    }
    httpPost.setEntity(mpBuilder.build());

    return UnmarshallUtil.unmarshall(getXmlTransformedResponse(httpPost));
}

From source file:org.wso2.identity.integration.test.utils.DataExtractUtil.java

/**
 * Return a query param value of a given key, from a URI string.
 *
 * @param URIString URI as a string   .//  ww  w  . j  av  a  2  s  . c o  m
 * @param key       Key that needs to be extracted.
 * @throws URISyntaxException
 * @return String value corresponds to the key.
 */
public static String getParamFromURIString(String URIString, String key) throws URISyntaxException {

    String param = null;
    List<NameValuePair> params = URLEncodedUtils.parse(new URI(URIString),
            String.valueOf(StandardCharsets.UTF_8));
    for (NameValuePair param1 : params) {
        if (StringUtils.equals(param1.getName(), key)) {
            param = param1.getValue();
            break;
        }
    }
    return param;
}