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");
}
}
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;
}
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() + ")");
}
}
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();
}
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);
}
}
Aggregations