Search in sources :

Example 56 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project wechat-mp-sdk by usc.

the class MediaUtil method uploadMedia.

// TODO-Shunli: now upload video always failed, tip system error, check later
public static MediaJsonRtn uploadMedia(License license, MediaFile mediaFile) {
    if (mediaFile == null) {
        return JsonRtnUtil.buildFailureJsonRtn(MediaJsonRtn.class, "missing mediaFile");
    }
    // maybe todo more mediaFile legality check
    String accessToken = AccessTokenUtil.getAccessToken(license);
    String url = WechatRequest.UPLOAD_MEDIA.getUrl();
    try {
        MediaType mediaType = mediaFile.getMediaType();
        URI uri = new URIBuilder(url).setParameter("access_token", accessToken).setParameter("type", mediaType.getName()).build();
        HttpEntity httpEntity = MultipartEntityBuilder.create().addBinaryBody("body", mediaFile.getFile()).build();
        String rtnJson = Request.Post(uri).connectTimeout(HttpUtil.CONNECT_TIMEOUT).socketTimeout(HttpUtil.SOCKET_TIMEOUT).body(httpEntity).execute().handleResponse(HttpUtil.UTF8_CONTENT_HANDLER);
        MediaJsonRtn jsonRtn = JsonRtnUtil.parseJsonRtn(rtnJson, MediaJsonRtn.class);
        log.info("upload media:\n url={},\n body={},\n rtn={},{}", uri, mediaFile, rtnJson, jsonRtn);
        return jsonRtn;
    } catch (Exception e) {
        String msg = "upload media failed:\n " + "url=" + url + "?access_token=" + accessToken + ",\n body=" + mediaFile;
        log.error(msg, e);
        return JsonRtnUtil.buildFailureJsonRtn(MediaJsonRtn.class, "uploadMedia failed");
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) MediaJsonRtn(org.usc.wechat.mp.sdk.vo.media.MediaJsonRtn) MediaType(org.usc.wechat.mp.sdk.vo.media.MediaType) URI(java.net.URI) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 57 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project openhab1-addons by openhab.

the class Tr064Comm method createTr064HttpClient.

/***
     * Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
     * and sets Auth. Scheme to Digest Auth
     *
     * @param fboxUrl the URL from config file of fbox to connect to
     * @return the ready-to-use httpclient for tr064 requests
     */
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);
    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
    // auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    // known from fbox specification
    digestAuth.overrideParamter("realm", "HTTPS Access");
    // never known at first request
    digestAuth.overrideParamter("nonce", "");
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);
    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        // accept self signed certs
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        // dont
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
    // verify
    // hostname
    // against
    // cert
    // CN
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
    // BUILDER
    // setup builder with parameters defined before
    hc = // set the SSL options which trust every self signed
    HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// set auth options using digest
    credp).setDefaultRequestConfig(// set the request config specifying timeout
    rc).build();
    return hc;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) URISyntaxException(java.net.URISyntaxException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) SOAPException(javax.xml.soap.SOAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 58 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project spring-boot by spring-projects.

the class ProjectGenerationRequest method generateUrl.

/**
	 * Generates the URI to use to generate a project represented by this request.
	 * @param metadata the metadata that describes the service
	 * @return the project generation URI
	 */
URI generateUrl(InitializrServiceMetadata metadata) {
    try {
        URIBuilder builder = new URIBuilder(this.serviceUrl);
        StringBuilder sb = new StringBuilder();
        if (builder.getPath() != null) {
            sb.append(builder.getPath());
        }
        ProjectType projectType = determineProjectType(metadata);
        this.type = projectType.getId();
        sb.append(projectType.getAction());
        builder.setPath(sb.toString());
        if (!this.dependencies.isEmpty()) {
            builder.setParameter("dependencies", StringUtils.collectionToCommaDelimitedString(this.dependencies));
        }
        if (this.groupId != null) {
            builder.setParameter("groupId", this.groupId);
        }
        String resolvedArtifactId = resolveArtifactId();
        if (resolvedArtifactId != null) {
            builder.setParameter("artifactId", resolvedArtifactId);
        }
        if (this.version != null) {
            builder.setParameter("version", this.version);
        }
        if (this.name != null) {
            builder.setParameter("name", this.name);
        }
        if (this.description != null) {
            builder.setParameter("description", this.description);
        }
        if (this.packageName != null) {
            builder.setParameter("packageName", this.packageName);
        }
        if (this.type != null) {
            builder.setParameter("type", projectType.getId());
        }
        if (this.packaging != null) {
            builder.setParameter("packaging", this.packaging);
        }
        if (this.javaVersion != null) {
            builder.setParameter("javaVersion", this.javaVersion);
        }
        if (this.language != null) {
            builder.setParameter("language", this.language);
        }
        if (this.bootVersion != null) {
            builder.setParameter("bootVersion", this.bootVersion);
        }
        return builder.build();
    } catch (URISyntaxException e) {
        throw new ReportableException("Invalid service URL (" + e.getMessage() + ")");
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 59 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project feign by OpenFeign.

the class ApacheHttpClient method toHttpUriRequest.

HttpUriRequest toHttpUriRequest(Request request, Request.Options options) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException {
    RequestBuilder requestBuilder = RequestBuilder.create(request.method());
    //per request timeouts
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(options.connectTimeoutMillis()).setSocketTimeout(options.readTimeoutMillis()).build();
    requestBuilder.setConfig(requestConfig);
    URI uri = new URIBuilder(request.url()).build();
    requestBuilder.setUri(uri.getScheme() + "://" + uri.getAuthority() + uri.getRawPath());
    //request query params
    List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, requestBuilder.getCharset().name());
    for (NameValuePair queryParam : queryParams) {
        requestBuilder.addParameter(queryParam);
    }
    //request headers
    boolean hasAcceptHeader = false;
    for (Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
        String headerName = headerEntry.getKey();
        if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
            hasAcceptHeader = true;
        }
        if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
            // doesn't like us to set it as well.
            continue;
        }
        for (String headerValue : headerEntry.getValue()) {
            requestBuilder.addHeader(headerName, headerValue);
        }
    }
    //some servers choke on the default accept string, so we'll set it to anything
    if (!hasAcceptHeader) {
        requestBuilder.addHeader(ACCEPT_HEADER_NAME, "*/*");
    }
    //request body
    if (request.body() != null) {
        HttpEntity entity = null;
        if (request.charset() != null) {
            ContentType contentType = getContentType(request);
            String content = new String(request.body(), request.charset());
            entity = new StringEntity(content, contentType);
        } else {
            entity = new ByteArrayEntity(request.body());
        }
        requestBuilder.setEntity(entity);
    }
    return requestBuilder.build();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) NameValuePair(org.apache.http.NameValuePair) RequestBuilder(org.apache.http.client.methods.RequestBuilder) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map)

Example 60 with URIBuilder

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

the class KMSClientProvider method createURL.

private URL createURL(String collection, String resource, String subResource, Map<String, ?> parameters) throws IOException {
    try {
        StringBuilder sb = new StringBuilder();
        sb.append(kmsUrl);
        if (collection != null) {
            sb.append(collection);
            if (resource != null) {
                sb.append("/").append(URLEncoder.encode(resource, UTF8));
                if (subResource != null) {
                    sb.append("/").append(subResource);
                }
            }
        }
        URIBuilder uriBuilder = new URIBuilder(sb.toString());
        if (parameters != null) {
            for (Map.Entry<String, ?> param : parameters.entrySet()) {
                Object value = param.getValue();
                if (value instanceof String) {
                    uriBuilder.addParameter(param.getKey(), (String) value);
                } else {
                    for (String s : (String[]) value) {
                        uriBuilder.addParameter(param.getKey(), s);
                    }
                }
            }
        }
        return uriBuilder.build().toURL();
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap) URIBuilder(org.apache.http.client.utils.URIBuilder)

Aggregations

URIBuilder (org.apache.http.client.utils.URIBuilder)107 URISyntaxException (java.net.URISyntaxException)42 URI (java.net.URI)37 HttpGet (org.apache.http.client.methods.HttpGet)22 IOException (java.io.IOException)21 NameValuePair (org.apache.http.NameValuePair)13 HttpEntity (org.apache.http.HttpEntity)10 NotNull (org.jetbrains.annotations.NotNull)9 Map (java.util.Map)8 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)8 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 HttpResponse (org.apache.http.HttpResponse)7 List (java.util.List)6 HttpClient (org.apache.http.client.HttpClient)5 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)5 Gson (com.google.gson.Gson)4 URL (java.net.URL)4 RequestConfig (org.apache.http.client.config.RequestConfig)4 HttpPost (org.apache.http.client.methods.HttpPost)4