org.apache.http.client.utils.URIBuilder#build ( )源码实例Demo

下面列出了org.apache.http.client.utils.URIBuilder#build ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: davmail   文件: HC4ExchangeFormAuthenticator.java
protected URI getAbsoluteUri(URI uri, String path) throws URISyntaxException {
    URIBuilder uriBuilder = new URIBuilder(uri);
    if (path != null) {
        // reset query string
        uriBuilder.clearParameters();
        if (path.startsWith("/")) {
            // path is absolute, replace method path
            uriBuilder.setPath(path);
        } else if (path.startsWith("http://") || path.startsWith("https://")) {
            return URI.create(path);
        } else {
            // relative path, build new path
            String currentPath = uri.getPath();
            int end = currentPath.lastIndexOf('/');
            if (end >= 0) {
                uriBuilder.setPath(currentPath.substring(0, end + 1) + path);
            } else {
                throw new URISyntaxException(uriBuilder.build().toString(), "Invalid path");
            }
        }
    }
    return uriBuilder.build();
}
 
源代码2 项目: data-prep   文件: FolderChildrenList.java
private HttpRequestBase onExecute(final String parentId, final Sort sort, final Order order) {
    try {
        String uri = preparationServiceUrl + "/folders";
        final URIBuilder uriBuilder = new URIBuilder(uri);
        if (parentId != null) {
            uriBuilder.addParameter("parentId", parentId);
        }
        if (sort != null) {
            uriBuilder.addParameter("sort", sort.camelName());
        }
        if (order != null) {
            uriBuilder.addParameter("order", order.camelName());
        }

        return new HttpGet(uriBuilder.build());

    } catch (URISyntaxException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}
 
源代码3 项目: org.hl7.fhir.core   文件: ResourceAddress.java
public static URI buildEndpointUriFromString(String endpointPath) {
	URI uri = null; 
	try {
		URIBuilder uriBuilder = new URIBuilder(endpointPath);
		uri = uriBuilder.build();
		String scheme = uri.getScheme();
		String host = uri.getHost();
		if(!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https")) {
			throw new EFhirClientException("Scheme must be 'http' or 'https': " + uri);
		}
		if(StringUtils.isBlank(host)) {
			throw new EFhirClientException("host cannot be blank: " + uri);
		}
	} catch(URISyntaxException e) {
		throw new EFhirClientException("Invalid URI", e);
	}
	return uri;
}
 
源代码4 项目: knox   文件: ScannerGetNext.java
@Override
protected Callable<Response> callable() {
  return new Callable<Response>() {
    @Override
    public Response call() throws Exception {
      URIBuilder uri = uri( HBase.SERVICE_PATH, "/", tableName, "/scanner/", scannerId );
      HttpGet get = new HttpGet( uri.build() );
      get.setHeader( "Accept", "application/json" );
      return new Response( execute( get ) );
    }
  };
}
 
源代码5 项目: netcdf-java   文件: HTTPUtil.java
/**
 * Remove selected fields from a URI producing a new URI
 *
 * @param uri the uri to convert
 * @param excludes the parts to exclude
 * @return The new URI instance
 */
static URI uriExclude(final URI uri, URIPart... excludes) {
  URIBuilder urib = new URIBuilder();
  EnumSet<URIPart> set = EnumSet.of(excludes[0], excludes);
  for (URIPart part : URIPart.values()) {
    if (set.contains(part))
      continue;
    switch (part) {
      case SCHEME:
        urib.setScheme(uri.getScheme());
        break;
      case USERINFO:
        urib.setUserInfo(uri.getRawUserInfo());
        break;
      case HOST:
        urib.setHost(uri.getHost());
        break;
      case PORT:
        urib.setPort(uri.getPort());
        break;
      case PATH:
        urib.setPath(uri.getPath());
        break;
      case QUERY:
        urib.setCustomQuery(uri.getQuery());
        break;
      case FRAGMENT:
        urib.setFragment(uri.getFragment());
        break;
    }
  }
  try {
    return urib.build();
  } catch (URISyntaxException e) {
    throw new IllegalArgumentException(e.getMessage());
  }
}
 
源代码6 项目: geoportal-server-harvester   文件: AgpClient.java
/**
 * Lists folders.
 * @param owner owner
 * @param token token
 * @return array of folders
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public FolderEntry[] listFolders(String owner, String token) throws URISyntaxException, IOException {
  URIBuilder builder = new URIBuilder(userUri(owner, null));
  
  builder.setParameter("f", "json");
  if (token!=null) {
    builder.setParameter("token", token);
  }
  HttpGet req = new HttpGet(builder.build());
  
  return execute(req,ContentResponse.class).folders;
}
 
源代码7 项目: levelup-java-examples   文件: ConstructBuildURI.java
@Test
public void contruct_uri_apache () throws URISyntaxException {
	
	URIBuilder builder = new URIBuilder()
			.setScheme("http")
			.setHost("www.leveluplunch.com")
			.setPath("/java/examples/");
	
	URI uri = builder.build();
	
	assertEquals(
			"http://www.leveluplunch.com/java/examples/", 
			uri.toString());
}
 
源代码8 项目: geoportal-server-harvester   文件: AgpClient.java
private URI userUri(String owner, String folderId) throws URISyntaxException {
  URIBuilder builder = new URIBuilder();
  builder.setScheme(rootUrl.toURI().getScheme())
         .setHost(rootUrl.toURI().getHost())
         .setPort(rootUrl.toURI().getPort())
         .setPath(rootUrl.toURI().getPath() + "sharing/rest/content/users/" + owner + (folderId!=null? "/"+folderId: ""));
  return builder.build();
}
 
/**
 * Builds the URI from the URI parameter hash
 * <p>
 * This will append each of the {key, value} pairs in uriParamsHash to the URI.
 * 
 * @param uriParamsHash the hashtable containing parameters to be added to the URI for making the call to TMDB
 * @return URI for making the HTTP call to TMDB API
 * @throws URISyntaxException if the uri being built is in the incorrect format
 */
private static URI buildUriStringFromParamsHash(Hashtable<String, String> uriParamsHash, String path) throws URISyntaxException {
    URIBuilder urib = new URIBuilder();
    urib.setScheme("http"); //$NON-NLS-1$
    urib.setHost(TMDB_BASE_URL);
    urib.setPath(path);
    urib.addParameter("api_key", themoviedbapikey); //$NON-NLS-1$
    if (uriParamsHash != null) {
        Set<String> keys = uriParamsHash.keySet();
        for (String key : keys) {
            urib.addParameter(key, uriParamsHash.get(key));
        }
    }
    return urib.build();
}
 
源代码10 项目: knox   文件: AppState.java
@Override
protected Callable<Response> callable() {
    return new Callable<Response>() {
        @Override
        public Response call() throws Exception {
            URIBuilder uri = uri( Yarn.SERVICE_PATH, "/v1/cluster/apps/", appId, "/state" );
            HttpGet request = new HttpGet( uri.build() );
            return new Response( execute( request ) );
        }
    };
}
 
源代码11 项目: org.hl7.fhir.core   文件: ResourceAddress.java
public static URI appendQueryStringToUri(URI uri, String parameterName, String parameterValue) {
	URI modifiedUri = null;
	try {
		URIBuilder uriBuilder = new URIBuilder(uri);
		uriBuilder.setQuery(parameterName + "=" + parameterValue);
		modifiedUri = uriBuilder.build();
	} catch(Exception e) {
		throw new EFhirClientException("Unable to append query parameter '" + parameterName + "=" + parameterValue + " to URI " + uri, e);
	}
	return modifiedUri;
}
 
源代码12 项目: data-prep   文件: DataSetGetMetadataLegacy.java
private void configureSampleDataset(String dataSetId) {
    URI uri;
    try {
        final URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl);
        uriBuilder.setPath(uriBuilder.getPath() + "/datasets/" + dataSetId + "/sample/metadata");
        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }

    execute(() -> new HttpGet(uri));
    on(HttpStatus.OK).then(convertResponse(objectMapper, DataSetMetadata.class));
}
 
源代码13 项目: knox   文件: Rename.java
@Override
protected Callable<Rename.Response> callable() {
  return new Callable<Rename.Response>() {
    @Override
    public Rename.Response call() throws Exception {
      URIBuilder uri = uri(Hdfs.SERVICE_PATH, file);
      addQueryParam(uri, "op", "RENAME");
      addQueryParam(uri, "destination", to);
      HttpPut request = new HttpPut(uri.build());
      return new Rename.Response(execute(request));
    }
  };
}
 
源代码14 项目: davmail   文件: O365Authenticator.java
public static String buildAuthorizeUrl(String tenantId, String clientId, String redirectUri, String username) throws IOException {
    URI uri;
    try {
        URIBuilder uriBuilder = new URIBuilder()
                .setScheme("https")
                .setHost("login.microsoftonline.com")
                .addParameter("client_id", clientId)
                .addParameter("response_type", "code")
                .addParameter("redirect_uri", redirectUri)
                .addParameter("response_mode", "query")
                .addParameter("login_hint", username);

        // force consent
        //uriBuilder.addParameter("prompt", "consent")
        // switch to new v2.0 OIDC compliant endpoint https://docs.microsoft.com/en-us/azure/active-directory/develop/azure-ad-endpoint-comparison
        if (Settings.getBooleanProperty("davmail.enableOidc", false)) {
            uriBuilder.setPath("/" + tenantId + "/oauth2/v2.0/authorize")
                    .addParameter("scope", "openid https://outlook.office365.com/EWS.AccessAsUser.All");
        } else {
            uriBuilder.setPath("/" + tenantId + "/oauth2/authorize")
                    .addParameter("resource", RESOURCE);
        }

        uri = uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    return uri.toString();
}
 
源代码15 项目: snowflake-ingest-java   文件: RequestBuilder.java
/**
 * makeHistoryURI - Given a request UUID, and a fully qualified pipe name
 * make a URI for the history reporting
 *
 * @param requestId the label for this request
 * @param pipe the pipe name
 * @param recentSeconds history only for items in the recentSeconds window
 * @param beginMark mark from which history should be fetched
 * @return URI for the insert request
 */
private URI makeHistoryURI(UUID requestId,
                           String pipe,
                           Integer recentSeconds,
                           String beginMark)
              throws URISyntaxException
{
  //if the table name is null, we have to abort
  if (pipe == null)
  {
    throw new IllegalArgumentException();
  }

  //get the base endpoint UIR
  URIBuilder builder = makeBaseURI(requestId);

  //set the path for the URI
  builder.setPath(String.format(HISTORY_ENDPOINT_FORMAT, pipe));

  if (recentSeconds != null)
  {
    builder.setParameter(RECENT_HISTORY_IN_SECONDS,
                         String.valueOf(recentSeconds));
  }

  if (beginMark != null)
  {
    builder.setParameter(HISTORY_BEGIN_MARK, beginMark);
  }

  LOGGER.info("Final History URIBuilder - {}", builder.toString());
  //build the final URI
  return builder.build();
}
 
源代码16 项目: moon-api-gateway   文件: ProxyServiceTest.java
@Test
public void testCallHttpGet_API_TRANSFER_MODE() throws Exception {

    HttpClient httpClient = HttpClientBuilder.create().build();

    //inbound path : /stackoverflow/2.2/question/:path
    //outbound path : http://api.stackexchange.com/2.2/questions
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http")
            .setHost("localhost")
            .setPort(8080)
            .setPath("/stackoverflow/2.2/question/test")
            //Insert mandatory query param
            .setParameter("site", "stackoverflow")
            //Insert option query param
            .setParameter("page", "2")
            .setParameter("votes", "1");


    HttpGet httpGet = new HttpGet(uriBuilder.build());

    //this action is not needed. just for understanding.
    httpGet.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON.toString());
    httpGet.setHeader("apiKey", "1000-1000-1000-1000");

    HttpResponse response = httpClient.execute(httpGet);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    response.getEntity().writeTo(outputStream);
    logger.info("Response: {}", outputStream);

    assertThat(response.containsHeader(HttpHeaders.CONTENT_TYPE), is(true));
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
 
源代码17 项目: render   文件: RenderDataClient.java
/**
 * @param  stack  name of stack.
 * @param  minZ   (optional) only include layers with z values greater than or equal to this minimum.
 * @param  maxZ   (optional) only include layers with z values less than or equal to this maximum.
 *
 * @return section data for set of layers in the specified stack.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public List<SectionData> getStackSectionData(final String stack,
                                             final Double minZ,
                                             final Double maxZ)
        throws IOException {

    final URIBuilder builder = new URIBuilder(getUri(urls.getStackUrlString(stack) + "/sectionData"));

    if (minZ != null) {
        builder.addParameter("minZ", minZ.toString());
    }
    if (maxZ != null) {
        builder.addParameter("maxZ", maxZ.toString());
    }

    final URI uri;
    try {
        uri = builder.build();
    } catch (final URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }

    final HttpGet httpGet = new HttpGet(uri);
    final String requestContext = "GET " + uri;
    final TypeReference<List<SectionData>> typeReference = new TypeReference<List<SectionData>>() {};
    final JsonUtils.GenericHelper<List<SectionData>> helper = new JsonUtils.GenericHelper<>(typeReference);
    final JsonResponseHandler<List<SectionData>> responseHandler = new JsonResponseHandler<>(requestContext, helper);

    LOG.info("getStackSectionData: submitting {}", requestContext);

    return httpClient.execute(httpGet, responseHandler);
}
 
源代码18 项目: owltools   文件: AbstractRetrieveGolr.java
URI createGolrRequest(List<String []> tagvalues, String category, int start, int pagination) throws IOException {
	try {
		URIBuilder builder = new URIBuilder(server);
		String currentPath = StringUtils.trimToEmpty(builder.getPath());
		builder.setPath(currentPath+"/select");
		builder.addParameter("defType", "edismax");
		builder.addParameter("qt", "standard");
		builder.addParameter("wt", "json");
		if (isIndentJson()) {
			builder.addParameter("indent","on");
		}
		builder.addParameter("fl",StringUtils.join(getRelevantFields(), ','));
		builder.addParameter("facet","false");
		builder.addParameter("json.nl","arrarr");
		builder.addParameter("q","*:*");
		builder.addParameter("rows", Integer.toString(pagination));
		builder.addParameter("start", Integer.toString(start));
		builder.addParameter("fq", "document_category:\""+category+"\"");
		for (String [] tagvalue : tagvalues) {
			if (tagvalue.length == 2) {
				builder.addParameter("fq", tagvalue[0]+":\""+tagvalue[1]+"\"");
			}
			else if (tagvalue.length > 2) {
				// if there is more than one value, assume that this is an OR query
				StringBuilder value = new StringBuilder();
				value.append(tagvalue[0]).append(":(");
				for (int i = 1; i < tagvalue.length; i++) {
					if (i > 1) {
						value.append(" OR ");
					}
					value.append('"').append(tagvalue[i]).append('"');
				}
				value.append(')');
				builder.addParameter("fq", value.toString());
			}
		}
		return builder.build();
	} catch (URISyntaxException e) {
		throw new IOException("Could not build URI for Golr request", e);
	}
}
 
源代码19 项目: herd   文件: UploaderWebClient.java
/**
 * Retrieves all versions for the specified business object data key.
 *
 * @param businessObjectDataKey the business object data key
 *
 * @return {@link org.finra.herd.model.api.xml.BusinessObjectDataVersions}
 * @throws JAXBException if a JAXB error was encountered
 * @throws IOException if an I/O error was encountered
 * @throws URISyntaxException if a URI syntax error was encountered
 * @throws KeyStoreException if a key store exception occurs
 * @throws NoSuchAlgorithmException if a no such algorithm exception occurs
 * @throws KeyManagementException if key management exception
 */
public BusinessObjectDataVersions getBusinessObjectDataVersions(BusinessObjectDataKey businessObjectDataKey)
    throws URISyntaxException, IOException, JAXBException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException
{
    LOGGER.info("Retrieving business object data versions from the registration server...");

    BusinessObjectDataVersions businessObjectDataVersions;
    try (CloseableHttpClient client = httpClientHelper
        .createHttpClient(regServerAccessParamsDto.isTrustSelfSignedCertificate(), regServerAccessParamsDto.isDisableHostnameVerification()))
    {
        StringBuilder uriPathBuilder = new StringBuilder(300);
        uriPathBuilder.append(HERD_APP_REST_URI_PREFIX);
        uriPathBuilder.append("/businessObjectData/namespaces/").append(businessObjectDataKey.getNamespace());
        uriPathBuilder.append("/businessObjectDefinitionNames/").append(businessObjectDataKey.getBusinessObjectDefinitionName());
        uriPathBuilder.append("/businessObjectFormatUsages/").append(businessObjectDataKey.getBusinessObjectFormatUsage());
        uriPathBuilder.append("/businessObjectFormatFileTypes/").append(businessObjectDataKey.getBusinessObjectFormatFileType());
        uriPathBuilder.append("/versions");

        URIBuilder uriBuilder = new URIBuilder().setScheme(getUriScheme()).setHost(regServerAccessParamsDto.getRegServerHost())
            .setPort(regServerAccessParamsDto.getRegServerPort()).setPath(uriPathBuilder.toString())
            .setParameter("partitionValue", businessObjectDataKey.getPartitionValue());

        if (businessObjectDataKey.getSubPartitionValues() != null)
        {
            uriBuilder.setParameter("subPartitionValues", herdStringHelper.join(businessObjectDataKey.getSubPartitionValues(), "|", "\\"));
        }

        if (businessObjectDataKey.getBusinessObjectFormatVersion() != null)
        {
            uriBuilder.setParameter("businessObjectFormatVersion", businessObjectDataKey.getBusinessObjectFormatVersion().toString());
        }

        if (businessObjectDataKey.getBusinessObjectDataVersion() != null)
        {
            uriBuilder.setParameter("businessObjectDataVersion", businessObjectDataKey.getBusinessObjectDataVersion().toString());
        }

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accepts", DEFAULT_ACCEPT);

        // If SSL is enabled, set the client authentication header.
        if (regServerAccessParamsDto.isUseSsl())
        {
            httpGet.addHeader(getAuthorizationHeader());
        }

        LOGGER.info(String.format("    HTTP GET URI: %s", httpGet.getURI().toString()));

        businessObjectDataVersions = getBusinessObjectDataVersions(httpClientOperations.execute(client, httpGet));
    }

    LOGGER.info(String.format("Successfully retrieved %d already registered version(s) for the business object data. businessObjectDataKey=%s",
        businessObjectDataVersions.getBusinessObjectDataVersions().size(), jsonHelper.objectToJson(businessObjectDataKey)));

    return businessObjectDataVersions;
}
 
源代码20 项目: render   文件: RenderDataClient.java
/**
 * Clones the specified stack.
 *
 * @param  fromStack       source stack to clone.
 * @param  toProject       project for new stack with cloned data (null if same as source project).
 * @param  toStack         new stack to hold cloned data.
 * @param  toStackVersion  version data for the new stack.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public void cloneStackVersion(final String fromStack,
                              final String toProject,
                              final String toStack,
                              final StackVersion toStackVersion,
                              final Boolean skipTransforms,
                              final List<Double> zValues)
        throws IOException {

    final String json = toStackVersion.toJson();
    final StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);

    final URIBuilder builder = new URIBuilder(getUri(urls.getCloneToUrlString(fromStack, toStack)));

    if (zValues != null) {
        for (final Double z : zValues) {
            builder.addParameter("z", z.toString());
        }
    }

    if (toProject != null) {
        builder.addParameter("toProject", toProject);
    }

    if (skipTransforms != null) {
        builder.addParameter("skipTransforms", skipTransforms.toString());
    }

    final URI uri;
    try {
        uri = builder.build();
    } catch (final URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }

    final String requestContext = "PUT " + uri;
    final ResourceCreatedResponseHandler responseHandler = new ResourceCreatedResponseHandler(requestContext);

    final HttpPut httpPut = new HttpPut(uri);
    httpPut.setEntity(stringEntity);

    LOG.info("cloneStackVersion: submitting {}", requestContext);

    httpClient.execute(httpPut, responseHandler);
}