Search in sources :

Example 1 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project elasticsearch by elastic.

the class RestClientSingleHostTests method performRandomRequest.

private HttpUriRequest performRandomRequest(String method) throws Exception {
    String uriAsString = "/" + randomStatusCode(getRandom());
    URIBuilder uriBuilder = new URIBuilder(uriAsString);
    final Map<String, String> params = new HashMap<>();
    boolean hasParams = randomBoolean();
    if (hasParams) {
        int numParams = randomIntBetween(1, 3);
        for (int i = 0; i < numParams; i++) {
            String paramKey = "param-" + i;
            String paramValue = randomAsciiOfLengthBetween(3, 10);
            params.put(paramKey, paramValue);
            uriBuilder.addParameter(paramKey, paramValue);
        }
    }
    if (randomBoolean()) {
        //randomly add some ignore parameter, which doesn't get sent as part of the request
        String ignore = Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
        if (randomBoolean()) {
            ignore += "," + Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
        }
        params.put("ignore", ignore);
    }
    URI uri = uriBuilder.build();
    HttpUriRequest request;
    switch(method) {
        case "DELETE":
            request = new HttpDeleteWithEntity(uri);
            break;
        case "GET":
            request = new HttpGetWithEntity(uri);
            break;
        case "HEAD":
            request = new HttpHead(uri);
            break;
        case "OPTIONS":
            request = new HttpOptions(uri);
            break;
        case "PATCH":
            request = new HttpPatch(uri);
            break;
        case "POST":
            request = new HttpPost(uri);
            break;
        case "PUT":
            request = new HttpPut(uri);
            break;
        case "TRACE":
            request = new HttpTrace(uri);
            break;
        default:
            throw new UnsupportedOperationException("method not supported: " + method);
    }
    HttpEntity entity = null;
    boolean hasBody = request instanceof HttpEntityEnclosingRequest && getRandom().nextBoolean();
    if (hasBody) {
        entity = new StringEntity(randomAsciiOfLengthBetween(10, 100), ContentType.APPLICATION_JSON);
        ((HttpEntityEnclosingRequest) request).setEntity(entity);
    }
    Header[] headers = new Header[0];
    final Set<String> uniqueNames = new HashSet<>();
    if (randomBoolean()) {
        headers = RestClientTestUtil.randomHeaders(getRandom(), "Header");
        for (Header header : headers) {
            request.addHeader(header);
            uniqueNames.add(header.getName());
        }
    }
    for (Header defaultHeader : defaultHeaders) {
        // request level headers override default headers
        if (uniqueNames.contains(defaultHeader.getName()) == false) {
            request.addHeader(defaultHeader);
        }
    }
    try {
        if (hasParams == false && hasBody == false && randomBoolean()) {
            restClient.performRequest(method, uriAsString, headers);
        } else if (hasBody == false && randomBoolean()) {
            restClient.performRequest(method, uriAsString, params, headers);
        } else {
            restClient.performRequest(method, uriAsString, params, entity, headers);
        }
    } catch (ResponseException e) {
    //all good
    }
    return request;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) HttpOptions(org.apache.http.client.methods.HttpOptions) URI(java.net.URI) HttpHead(org.apache.http.client.methods.HttpHead) HttpPatch(org.apache.http.client.methods.HttpPatch) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) HashSet(java.util.HashSet) URIBuilder(org.apache.http.client.utils.URIBuilder) HttpTrace(org.apache.http.client.methods.HttpTrace) Header(org.apache.http.Header)

Example 2 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project elasticsearch by elastic.

the class RestClient method buildUri.

private static URI buildUri(String pathPrefix, String path, Map<String, String> params) {
    Objects.requireNonNull(path, "path must not be null");
    try {
        String fullPath;
        if (pathPrefix != null) {
            if (path.startsWith("/")) {
                fullPath = pathPrefix + path;
            } else {
                fullPath = pathPrefix + "/" + path;
            }
        } else {
            fullPath = path;
        }
        URIBuilder uriBuilder = new URIBuilder(fullPath);
        for (Map.Entry<String, String> param : params.entrySet()) {
            uriBuilder.addParameter(param.getKey(), param.getValue());
        }
        return uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 3 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project opennms by OpenNMS.

the class HttpUrlConnection method getInputStream.

/* (non-Javadoc)
     * @see java.net.URLConnection#getInputStream()
     */
@Override
public InputStream getInputStream() throws IOException {
    try {
        if (m_clientWrapper == null) {
            connect();
        }
        // Build URL
        int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort();
        URIBuilder ub = new URIBuilder();
        ub.setPort(port);
        ub.setScheme(m_url.getProtocol());
        ub.setHost(m_url.getHost());
        ub.setPath(m_url.getPath());
        if (m_url.getQuery() != null && !m_url.getQuery().trim().isEmpty()) {
            final List<NameValuePair> params = URLEncodedUtils.parse(m_url.getQuery(), StandardCharsets.UTF_8);
            if (!params.isEmpty()) {
                ub.addParameters(params);
            }
        }
        // Build Request
        HttpRequestBase request = null;
        if (m_request != null && m_request.getMethod().equalsIgnoreCase("post")) {
            final Content cnt = m_request.getContent();
            HttpPost post = new HttpPost(ub.build());
            ContentType contentType = ContentType.create(cnt.getType());
            LOG.info("Processing POST request for {}", contentType);
            if (contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                FormFields fields = JaxbUtils.unmarshal(FormFields.class, cnt.getData());
                post.setEntity(fields.getEntity());
            } else {
                StringEntity entity = new StringEntity(cnt.getData(), contentType);
                post.setEntity(entity);
            }
            request = post;
        } else {
            request = new HttpGet(ub.build());
        }
        if (m_request != null) {
            // Add Custom Headers
            for (final Header header : m_request.getHeaders()) {
                request.addHeader(header.getName(), header.getValue());
            }
        }
        // Get Response
        CloseableHttpResponse response = m_clientWrapper.execute(request);
        return response.getEntity().getContent();
    } catch (Exception e) {
        throw new IOException("Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(), e);
    }
}
Also used : NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) ContentType(org.apache.http.entity.ContentType) HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) Header(org.opennms.protocols.xml.config.Header) Content(org.opennms.protocols.xml.config.Content) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 4 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project intellij-community by JetBrains.

the class EduAdaptiveStepicConnector method getAttempts.

private static List<StepicWrappers.AdaptiveAttemptWrapper.Attempt> getAttempts(@NotNull StepicUser user, int id) throws URISyntaxException, IOException {
    final URI attemptUrl = new URIBuilder(EduStepicNames.ATTEMPTS).addParameter("step", String.valueOf(id)).addParameter("user", String.valueOf(user.getId())).build();
    final StepicWrappers.AdaptiveAttemptContainer attempt = EduStepicAuthorizedClient.getFromStepic(attemptUrl.toString(), StepicWrappers.AdaptiveAttemptContainer.class, user);
    return attempt.attempts;
}
Also used : URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 5 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project intellij-community by JetBrains.

the class EduAdaptiveStepicConnector method getEnrolledCoursesIds.

@NotNull
public static List<Integer> getEnrolledCoursesIds(@NotNull StepicUser stepicUser) {
    try {
        final URI enrolledCoursesUri = new URIBuilder(EduStepicNames.COURSES).addParameter("enrolled", "true").build();
        final List<CourseInfo> courses = EduStepicAuthorizedClient.getFromStepic(enrolledCoursesUri.toString(), StepicWrappers.CoursesContainer.class, stepicUser).courses;
        final ArrayList<Integer> ids = new ArrayList<>();
        for (CourseInfo course : courses) {
            ids.add(course.getId());
        }
        return ids;
    } catch (IOException | URISyntaxException e) {
        LOG.warn(e.getMessage());
    }
    return Collections.emptyList();
}
Also used : IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

URIBuilder (org.apache.http.client.utils.URIBuilder)405 URISyntaxException (java.net.URISyntaxException)138 URI (java.net.URI)130 HttpGet (org.apache.http.client.methods.HttpGet)85 IOException (java.io.IOException)70 HttpResponse (org.apache.http.HttpResponse)49 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)49 NameValuePair (org.apache.http.NameValuePair)48 Test (org.junit.Test)45 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)43 ArrayList (java.util.ArrayList)39 HttpPost (org.apache.http.client.methods.HttpPost)37 Map (java.util.Map)36 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)36 lombok.val (lombok.val)32 List (java.util.List)23 HttpEntity (org.apache.http.HttpEntity)23 HashMap (java.util.HashMap)22 StringEntity (org.apache.http.entity.StringEntity)20 Header (org.apache.http.Header)19