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

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

源代码1 项目: render   文件: RenderDataClient.java
private List<CanvasMatches> getMatches(final String context,
                                       final String urlString,
                                       final boolean excludeMatchDetails)
        throws IOException {
    final URI uri;
    try {
        final URIBuilder builder = new URIBuilder(urlString);
        if (excludeMatchDetails) {
            builder.addParameter("excludeMatchDetails", String.valueOf(excludeMatchDetails));
        }
        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<CanvasMatches>> typeReference = new TypeReference<List<CanvasMatches>>() {};
    final JsonUtils.GenericHelper<List<CanvasMatches>> helper = new JsonUtils.GenericHelper<>(typeReference);
    final JsonResponseHandler<List<CanvasMatches>> responseHandler = new JsonResponseHandler<>(requestContext,
                                                                                               helper);

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

    return httpClient.execute(httpGet, responseHandler);
}
 
源代码2 项目: docker-java-api   文件: ListedContainers.java
@Override
public Iterator<Container> all() {
    final URIBuilder uriBuilder = new UncheckedUriBuilder(
        super.baseUri().toString().concat("/json")
    );
    uriBuilder.addParameter("all", "true");
    if (this.withSize) {
        uriBuilder.addParameter("size", "true");
    }
    final FilteredUriBuilder uri = new FilteredUriBuilder(
        uriBuilder,
        this.filters);

    return new ResourcesIterator<>(
        super.client(),
        new HttpGet(uri.build()),
        json -> new RtContainer(
            json,
            super.client(),
            URI.create(
                super.baseUri().toString() + "/" + json.getString("Id")
            ),
            super.docker()
        )
    );
}
 
源代码3 项目: celos   文件: CelosClient.java
public WorkflowStatus getWorkflowStatus(WorkflowID workflowID, ScheduledTime startTime, ScheduledTime endTime) throws Exception {

        URIBuilder uriBuilder = new URIBuilder(address);
        uriBuilder.setPath(uriBuilder.getPath() + WORKFLOW_SLOTS_PATH);
        if (endTime != null) {
            uriBuilder.addParameter(END_TIME_PARAM, timeFormatter.formatPretty(endTime));
        }
        if (startTime != null) {
            uriBuilder.addParameter(START_TIME_PARAM, timeFormatter.formatPretty(startTime));
        }
        uriBuilder.addParameter(ID_PARAM, workflowID.toString());
        URI uri = uriBuilder.build();

        HttpGet workflowListGet = new HttpGet(uri);
        HttpResponse getResponse = execute(workflowListGet);
        InputStream content = getResponse.getEntity().getContent();
        return parseWorkflowStatus(workflowID, content);
    }
 
源代码4 项目: flowable-engine   文件: CaseInstanceService.java
public JsonNode listCaseInstancesForCaseDefinition(ObjectNode bodyNode, ServerConfig serverConfig) {
    JsonNode resultNode = null;
    try {
        URIBuilder builder = new URIBuilder("cmmn-query/historic-case-instances");

        builder.addParameter("size", DEFAULT_CASEINSTANCE_SIZE);
        builder.addParameter("sort", "startTime");
        builder.addParameter("order", "desc");

        String uri = clientUtil.getUriWithPagingAndOrderParameters(builder, bodyNode);
        HttpPost post = clientUtil.createPost(uri, serverConfig);

        post.setEntity(clientUtil.createStringEntity(bodyNode.toString()));
        resultNode = clientUtil.executeRequest(post, serverConfig);
    } catch (Exception e) {
        throw new FlowableServiceException(e.getMessage(), e);
    }
    return resultNode;
}
 
源代码5 项目: axelor-open-suite   文件: KilometricService.java
/**
 * Get JSON response from YOURS(Yet Another Openstreetmap Route Service) API.
 *
 * @param origins
 * @param destinations
 * @return
 * @throws AxelorException
 * @throws JSONException
 * @throws URISyntaxException
 * @throws IOException
 */
protected JSONObject getYOURSApiResponse(String origins, String destinations)
    throws AxelorException, JSONException, URISyntaxException, IOException {

  Map<String, Object> originMap = this.getLocationMap(origins);
  Map<String, Object> destinationMap = this.getLocationMap(destinations);

  String flat = originMap.get("latitude").toString();
  String flon = originMap.get("longitude").toString();
  String tlat = destinationMap.get("latitude").toString();
  String tlon = destinationMap.get("longitude").toString();

  URIBuilder ub = new URIBuilder("http://www.yournavigation.org/api/1.0/gosmore.php");
  ub.addParameter("format", "geojson");
  ub.addParameter("flat", flat);
  ub.addParameter("flon", flon);
  ub.addParameter("tlat", tlat);
  ub.addParameter("tlon", tlon);
  ub.addParameter("v", "motorcar");
  ub.addParameter("fast", "0");
  return this.getApiResponse(ub.toString(), IExceptionMessage.KILOMETRIC_ALLOWANCE_OSM_ERROR);
}
 
源代码6 项目: pinpoint   文件: HttpRemoteService.java
private HttpGet createGet(String url, MultiValueMap<String, String> params) throws URISyntaxException {
    URIBuilder uri = new URIBuilder(url);

    for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        String key = entry.getKey();

        for (String value : entry.getValue()) {
            uri.addParameter(key, value);
        }
    }

    return new HttpGet(uri.build());
}
 
源代码7 项目: elucidate-server   文件: IRIBuilderServiceImpl.java
private String buildIri(String id, Map<String, Object> params) {
    try {
        URIBuilder builder = new URIBuilder(baseUrl);
        builder.setPath(String.format("%s/%s", builder.getPath(), id));
        if (params != null && !params.isEmpty()) {
            for (Entry<String, Object> param : params.entrySet()) {
                builder.addParameter(param.getKey(), String.valueOf(param.getValue()));
            }
        }
        return builder.toString();
    } catch (URISyntaxException e) {
        throw new InvalidIRIException(String.format("An error occurred building IRI with base URL [%s] with ID [%s] and parameters [%s]", baseUrl, id, params), e);
    }
}
 
源代码8 项目: celos   文件: CelosClient.java
/**
 * Deletes the specified register value.
 */
public void deleteRegister(BucketID bucket, RegisterKey key) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(address);
    uriBuilder.setPath(uriBuilder.getPath() + REGISTER_PATH);
    uriBuilder.addParameter(BUCKET_PARAM, bucket.toString());
    uriBuilder.addParameter(KEY_PARAM, key.toString());
    executeDelete(uriBuilder.build());
}
 
源代码9 项目: Quantum   文件: ReportUtils.java
private static void downloadExecutionSummaryReport(String deviceId, String driverExecutionId, String accessToken)
		throws Exception {
	URIBuilder uriBuilder = new URIBuilder(REPORTING_SERVER_URL + "/export/api/v1/test-executions/pdf");
	uriBuilder.addParameter("externalId[0]", driverExecutionId);
	// downloadFileAuthenticated(driverExecutionId, uriBuilder.build(),
	// ".pdf", "execution summary PDF report",
	// accessToken);
	downloadFileAuthenticated(deviceId + "_ExecutionSummaryReport", uriBuilder.build(), ".pdf",
			"execution summary PDF report", accessToken);

}
 
源代码10 项目: data-prep   文件: CreateChildFolder.java
private HttpRequestBase onExecute(final String parentId, final String path) {
    try {

        URIBuilder uriBuilder = new URIBuilder(preparationServiceUrl + "/folders");
        if (parentId != null) {
            uriBuilder.addParameter("parentId", parentId);
        }
        uriBuilder.addParameter("path", path);
        return new HttpPut(uriBuilder.build());
    } catch (URISyntaxException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}
 
/**
 * Creates uri with parameters for sharethrough request
 */
static String buildSharethroughUrl(String baseUri, String supplyId, String strVersion, String formattedDate,
                                   StrUriParameters params) {
    final URIBuilder uriBuilder = new URIBuilder()
            .setPath(baseUri)
            .addParameter("placement_key", params.getPkey())
            .addParameter("bidId", params.getBidID())
            .addParameter("consent_required", getBooleanStringValue(params.getConsentRequired()))
            .addParameter("consent_string", params.getConsentString())
            .addParameter("us_privacy", params.getUsPrivacySignal())
            .addParameter("instant_play_capable", getBooleanStringValue(params.getInstantPlayCapable()))
            .addParameter("stayInIframe", getBooleanStringValue(params.getIframe()))
            .addParameter("height", String.valueOf(params.getHeight()))
            .addParameter("width", String.valueOf(params.getWidth()))
            .addParameter("adRequestAt", formattedDate)
            .addParameter("supplyId", supplyId)
            .addParameter("strVersion", strVersion);

    final String ttduid = params.getTheTradeDeskUserId();
    if (StringUtils.isNotBlank(ttduid)) {
        uriBuilder.addParameter("ttduid", ttduid);
    }
    final String stxuid = params.getSharethroughUserId();
    if (StringUtils.isNotBlank(stxuid)) {
        uriBuilder.addParameter("stxuid", stxuid);
    }

    return uriBuilder.toString();
}
 
源代码12 项目: AndroidLocalizePlugin   文件: GoogleTranslator.java
@Override
public String query() throws Exception {
    URIBuilder uri = new URIBuilder(url);
    for (String key : formData.keySet()) {
        String value = formData.get(key);
        uri.addParameter(key, value);
    }
    HttpGet request = new HttpGet(uri.toString());

    RequestConfig.Builder builder = RequestConfig.copy(RequestConfig.DEFAULT)
            .setSocketTimeout(5000)
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000);

    if (PluginConfig.isEnableProxy()) {
        HttpHost proxy = new HttpHost(PluginConfig.getHostName(), PluginConfig.getPortNumber());
        builder.setProxy(proxy);
    }

    RequestConfig config = builder.build();
    request.setConfig(config);
    CloseableHttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();

    String result = EntityUtils.toString(entity, "UTF-8");
    EntityUtils.consume(entity);
    response.getEntity().getContent().close();
    response.close();

    return result;
}
 
源代码13 项目: owltools   文件: OWLServerSimSearchTest.java
protected HttpUriRequest createBogusRequest(int n) throws URISyntaxException {
	URIBuilder uriBuilder = new URIBuilder()
		.setScheme("http")
		.setHost("localhost").setPort(9031)
		.setPath("/owlsim/searchByAttributeSet/");
		
	uriBuilder.addParameter("a", "BOGUS:1234567");
	uriBuilder.addParameter("limit","5");
	URI uri = uriBuilder.build();
	LOG.info("Getting URL="+uri);
	HttpUriRequest httpUriRequest = new HttpGet(uri);
	LOG.info("Got URL="+uri);
	return httpUriRequest;
}
 
源代码14 项目: render   文件: RenderDataClient.java
/**
 * @param  stack  name of stack.
 * @param  minZ   (optional) minimum value to include in list.
 * @param  maxZ   (optional) maximum value to include in list.
 *
 * @return z values for the specified stack.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public List<Double> getStackZValues(final String stack,
                                    final Double minZ,
                                    final Double maxZ)
        throws IOException {

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

    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<Double>> typeReference = new TypeReference<List<Double>>() {};
    final JsonUtils.GenericHelper<List<Double>> helper = new JsonUtils.GenericHelper<>(typeReference);
    final JsonResponseHandler<List<Double>> responseHandler = new JsonResponseHandler<>(requestContext, helper);

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

    return httpClient.execute(httpGet, responseHandler);
}
 
源代码15 项目: geoportal-server-harvester   文件: Client.java
private URI createXmlUri(String id) throws URISyntaxException, IOException {
  URIBuilder b = new URIBuilder(url.toURI().resolve(REST_ITEM_URL + "/" + id + "/xml"));
  if (cred != null && !cred.isEmpty()) {
    b.addParameter("access_token", getAccessToken());
  }
  return b.build();
}
 
源代码16 项目: 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);
	}
}
 
源代码17 项目: james-project   文件: DownloadStepdefs.java
private Request queryParameterDownloadRequest(URIBuilder uriBuilder, String blobId, String username) throws URISyntaxException {
    AccessToken accessToken = userStepdefs.authenticate(username);
    AttachmentAccessTokenKey key = new AttachmentAccessTokenKey(username, blobId);
    uriBuilder.addParameter("access_token", attachmentAccessTokens.get(key).serialize());
    return Request.Get(uriBuilder.build());
}
 
源代码18 项目: geoportal-server-harvester   文件: Client.java
/**
 * Query ids.
 *
 * @param term term to query
 * @param value value of the term
 * @param batchSize batch size (note: size 1 indicates looking for the first
 * only)
 * @return listIds of ids
 * @throws IOException if reading response fails
 * @throws URISyntaxException if URL has invalid syntax
 */
private List<String> queryIds(String term, String value, long batchSize) throws IOException, URISyntaxException {
  Set<String> ids = new HashSet<>();
  String search_after = null;

  ObjectNode root = mapper.createObjectNode();
  root.put("size", batchSize);
  root.set("_source", mapper.createArrayNode().add("_id"));
  root.set("sort", mapper.createArrayNode().add(mapper.createObjectNode().put("_id", "asc")));
  if (term != null && value != null) {
    root.set("query", mapper.createObjectNode().set("match", mapper.createObjectNode().put(term, value)));
  }

  do {
    URIBuilder builder = new URIBuilder(url.toURI().resolve(createElasticSearchUrl()));
    if (cred != null && !cred.isEmpty()) {
      builder = builder.addParameter("access_token", getAccessToken());
    }
  
    if (search_after != null) {
      root.set("search_after", mapper.createArrayNode().add(search_after));
    }

    String json = mapper.writeValueAsString(root);
    HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

    QueryResponse response = query(builder, entity);
    if (response!=null && response.status!=null && response.status==400 && search_after==null) {
      // This indicates it could be an old version of Elastic Search behind the Geoportal.
      // Fall back to using scroll API
      return queryIdsScroll(term, value, batchSize);
    }

    search_after = null;
    if (response != null && response.hasHits()) {
      List<String> responseIds = response.hits.hits.stream().map(hit -> hit._id).collect(Collectors.toList());
      ids.addAll(responseIds);

      // if argument 'size' is 1 that means looking for the first one only; otherwise looking for every possible
      search_after = batchSize > 1 ? responseIds.get(responseIds.size() - 1) : null;
    }
  } while (search_after != null && !Thread.currentThread().isInterrupted());

  return ids.stream().collect(Collectors.toList());
}
 
/**
 * This method adds 'email' and 'password' parameters to the provided URIBuilder
 * Note: This credentials approach is very specific to the VIVO (https://github.com/vivo-project/VIVO)
 * application and should be refactored once another use-case/example is required.
 *
 * @param uriBuilder of SPARQL-Query endpoint
 */
private void addCredentials(URIBuilder uriBuilder) {
    if (username != null && password != null) {
        uriBuilder.addParameter("email", username);
        uriBuilder.addParameter("password", password);
    }
}
 
源代码20 项目: bbs   文件: HttpClientManage.java
/**
 * 执行带有参数的get请求
 *
 * @param url
 * @param paramMap
 * @return
 * @throws IOException
 * @throws URISyntaxException
 */
public String doGet(String url, Map<String, String> paramMap) throws IOException, URISyntaxException {
    URIBuilder builder = new URIBuilder(url);
    for (String s : paramMap.keySet()) {
        builder.addParameter(s, paramMap.get(s));
    }
    return doGet(builder.build().toString());
}