Search in sources :

Example 41 with NameValuePair

use of org.apache.hc.core5.http.copied.NameValuePair in project jahia by Jahia.

the class RenderTest method testRestAPI.

@Test
public void testRestAPI() throws RepositoryException, IOException, JSONException {
    JCRPublicationService jcrService = ServicesRegistry.getInstance().getJCRPublicationService();
    Locale englishLocale = LanguageCodeConverters.languageCodeToLocale("en");
    JCRSessionWrapper editSession = jcrService.getSessionFactory().getCurrentUserSession(Constants.EDIT_WORKSPACE, englishLocale);
    jcrService.getSessionFactory().getCurrentUserSession(Constants.LIVE_WORKSPACE, englishLocale);
    JCRNodeWrapper stageRootNode = editSession.getNode(SITECONTENT_ROOT_NODE);
    JCRNodeWrapper stageNode = stageRootNode.getNode("home");
    JCRNodeWrapper stagedPageContent = stageNode.getNode("listA");
    JCRNodeWrapper mainContent = stagedPageContent.addNode("mainContent", "jnt:mainContent");
    mainContent.setProperty(Constants.JCR_TITLE, MAIN_CONTENT_TITLE + "0");
    mainContent.setProperty("body", MAIN_CONTENT_BODY + "0");
    editSession.save();
    HttpPost createPost = new HttpPost(getBaseServerURL() + Jahia.getContextPath() + "/cms/render/default/en" + SITECONTENT_ROOT_NODE + "/home/listA/*");
    createPost.addHeader("x-requested-with", "XMLHttpRequest");
    createPost.addHeader("accept", "application/json");
    // here we voluntarily don't set the node name to test automatic name creation.
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("jcrNodeType", "jnt:mainContent"));
    nvps.add(new BasicNameValuePair(Constants.JCR_TITLE, MAIN_CONTENT_TITLE + "1"));
    nvps.add(new BasicNameValuePair("body", MAIN_CONTENT_BODY + "1"));
    createPost.setEntity(new UrlEncodedFormEntity(nvps));
    String responseBody = "";
    try (CloseableHttpResponse response = getHttpClient().execute(createPost)) {
        assertEquals("Error in response, code=" + response.getCode(), 201, response.getCode());
        responseBody = EntityUtils.toString(response.getEntity());
    } catch (ParseException e) {
        throw new IOException(e);
    }
    JSONObject jsonResults = new JSONObject(responseBody);
    assertNotNull("A proper JSONObject instance was expected, got null instead", jsonResults);
    assertTrue("body property should be " + MAIN_CONTENT_BODY + "1", jsonResults.get("body").equals(MAIN_CONTENT_BODY + "1"));
}
Also used : HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) NameValuePair(org.apache.hc.core5.http.NameValuePair) UrlEncodedFormEntity(org.apache.hc.client5.http.entity.UrlEncodedFormEntity) IOException(java.io.IOException) JSONObject(org.json.JSONObject) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) ParseException(org.apache.hc.core5.http.ParseException) Test(org.junit.Test)

Example 42 with NameValuePair

use of org.apache.hc.core5.http.copied.NameValuePair in project jahia by Jahia.

the class JahiaTestCase method post.

protected PostResult post(String url, String[]... params) throws IOException {
    HttpPost method = new HttpPost(url);
    method.addHeader("Origin", getBaseServerURL());
    List<NameValuePair> nvps = new ArrayList<>();
    for (String[] param : params) {
        nvps.add(new BasicNameValuePair(param[0], param[1]));
    }
    method.setEntity(new UrlEncodedFormEntity(nvps));
    int statusCode;
    String statusLine;
    String responseBody;
    try (CloseableHttpResponse response = getHttpClient().execute(method)) {
        statusCode = response.getCode();
        statusLine = response.getReasonPhrase();
        if (response.getCode() != HttpStatus.SC_OK) {
            logger.warn("Method failed: {} {}", response.getCode(), response.getReasonPhrase());
        }
        // Read the response body.
        responseBody = EntityUtils.toString(response.getEntity());
    } catch (ParseException e) {
        throw new IOException(e);
    }
    return new PostResult(statusCode, statusLine, responseBody);
}
Also used : HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) UrlEncodedFormEntity(org.apache.hc.client5.http.entity.UrlEncodedFormEntity) IOException(java.io.IOException) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)

Example 43 with NameValuePair

use of org.apache.hc.core5.http.copied.NameValuePair in project httpcomponents-core by apache.

the class ContentType method withParameters.

/**
 * Creates a new instance with this MIME type and the given parameters.
 *
 * @param params
 * @return a new instance with this MIME type and the given parameters.
 * @since 4.4
 */
public ContentType withParameters(final NameValuePair... params) throws UnsupportedCharsetException {
    if (params.length == 0) {
        return this;
    }
    final Map<String, String> paramMap = new LinkedHashMap<>();
    if (this.params != null) {
        for (final NameValuePair param : this.params) {
            paramMap.put(param.getName(), param.getValue());
        }
    }
    for (final NameValuePair param : params) {
        paramMap.put(param.getName(), param.getValue());
    }
    final List<NameValuePair> newParams = new ArrayList<>(paramMap.size() + 1);
    if (this.charset != null && !paramMap.containsKey(CHARSET)) {
        newParams.add(new BasicNameValuePair(CHARSET, this.charset.name()));
    }
    for (final Map.Entry<String, String> entry : paramMap.entrySet()) {
        newParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    return create(this.getMimeType(), newParams.toArray(EMPTY_NAME_VALUE_PAIR_ARRAY), true);
}
Also used : BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

Example 44 with NameValuePair

use of org.apache.hc.core5.http.copied.NameValuePair in project httpcomponents-core by apache.

the class URLEncodedUtils method parse.

/**
 * Returns a list of {@link NameValuePair}s parameters.
 *
 * @param s input text.
 * @param charset parameter charset.
 * @param separators parameter separators.
 * @return list of query parameters.
 *
 * @since 4.4
 */
public static List<NameValuePair> parse(final CharSequence s, final Charset charset, final char... separators) {
    Args.notNull(s, "Char sequence");
    final Tokenizer tokenParser = Tokenizer.INSTANCE;
    final BitSet delimSet = new BitSet();
    for (final char separator : separators) {
        delimSet.set(separator);
    }
    final Tokenizer.Cursor cursor = new Tokenizer.Cursor(0, s.length());
    final List<NameValuePair> list = new ArrayList<>();
    while (!cursor.atEnd()) {
        delimSet.set('=');
        final String name = tokenParser.parseToken(s, cursor, delimSet);
        String value = null;
        if (!cursor.atEnd()) {
            final int delim = s.charAt(cursor.getPos());
            cursor.updatePos(cursor.getPos() + 1);
            if (delim == '=') {
                delimSet.clear('=');
                value = tokenParser.parseToken(s, cursor, delimSet);
                if (!cursor.atEnd()) {
                    cursor.updatePos(cursor.getPos() + 1);
                }
            }
        }
        if (!name.isEmpty()) {
            list.add(new BasicNameValuePair(PercentCodec.decode(name, charset, true), PercentCodec.decode(value, charset, true)));
        }
    }
    return list;
}
Also used : NameValuePair(org.apache.hc.core5.http.NameValuePair) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) BitSet(java.util.BitSet) ArrayList(java.util.ArrayList) Tokenizer(org.apache.hc.core5.util.Tokenizer)

Example 45 with NameValuePair

use of org.apache.hc.core5.http.copied.NameValuePair in project httpcomponents-core by apache.

the class ClassicRequestBuilder method build.

@Override
public ClassicHttpRequest build() {
    String path = getPath();
    if (TextUtils.isEmpty(path)) {
        path = "/";
    }
    HttpEntity entityCopy = this.entity;
    final String method = getMethod();
    final List<NameValuePair> parameters = getParameters();
    if (parameters != null && !parameters.isEmpty()) {
        if (entityCopy == null && (Method.POST.isSame(method) || Method.PUT.isSame(method))) {
            entityCopy = HttpEntities.createUrlEncoded(parameters, getCharset());
        } else {
            try {
                final URI uri = new URIBuilder(path).setCharset(getCharset()).addParameters(parameters).build();
                path = uri.toASCIIString();
            } catch (final URISyntaxException ex) {
            // should never happen
            }
        }
    }
    if (entityCopy != null && Method.TRACE.isSame(method)) {
        throw new IllegalStateException(Method.TRACE + " requests may not include an entity");
    }
    final BasicClassicHttpRequest result = new BasicClassicHttpRequest(method, getScheme(), getAuthority(), path);
    result.setVersion(getVersion());
    result.setHeaders(getHeaders());
    result.setEntity(entityCopy);
    result.setAbsoluteRequestUri(isAbsoluteRequestUri());
    return result;
}
Also used : NameValuePair(org.apache.hc.core5.http.NameValuePair) HttpEntity(org.apache.hc.core5.http.HttpEntity) BasicClassicHttpRequest(org.apache.hc.core5.http.message.BasicClassicHttpRequest) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URIBuilder(org.apache.hc.core5.net.URIBuilder)

Aggregations

NameValuePair (org.apache.hc.core5.http.NameValuePair)56 Test (org.junit.jupiter.api.Test)26 BasicNameValuePair (org.apache.hc.core5.http.message.BasicNameValuePair)25 ArrayList (java.util.ArrayList)15 URI (java.net.URI)13 UrlEncodedFormEntity (org.apache.hc.client5.http.entity.UrlEncodedFormEntity)12 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)11 Map (java.util.Map)10 CharArrayBuffer (org.apache.hc.core5.util.CharArrayBuffer)9 IOException (java.io.IOException)7 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)7 URIBuilder (org.apache.hc.core5.net.URIBuilder)7 URISyntaxException (java.net.URISyntaxException)6 HashMap (java.util.HashMap)5 HeaderElement (org.apache.hc.core5.http.HeaderElement)5 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)4 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)4 List (java.util.List)3 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)3 HttpEntity (org.apache.hc.core5.http.HttpEntity)3