Java 类org.apache.http.client.utils.URIBuilder 实例源码

项目:outcomes    文件:TestHttpCore.java   
@Test
public void client() throws URISyntaxException, IOException {

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder()
            .setScheme("http")
            .setHost("www.google.com")
            .setPath("/search")
            .setParameter("q", "httpclient")
            .setParameter("btnG", "Google Search")
            .setParameter("aq", "f")
            .setParameter("oq", "")
            .build();
    HttpGet httpget = new HttpGet(uri);
    CloseableHttpResponse response = httpclient.execute(httpget);
}
项目:open-kilda    文件:Mininet.java   
/**
 * Simple Http Post.
 *
 * @param path the path
 * @param payload the payload
 * @return the closeable http response
 * @throws URISyntaxException the URI syntax exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MininetException the MininetException
 */
public CloseableHttpResponse simplePost(String path, String payload) 
    throws URISyntaxException, IOException, MininetException {
  URI uri = new URIBuilder()
      .setScheme("http")
      .setHost(mininetServerIP.toString())
      .setPort(mininetServerPort.getPort())
      .setPath(path)
      .build();
  CloseableHttpClient client = HttpClientBuilder.create().build();
  RequestConfig config = RequestConfig
      .custom()
      .setConnectTimeout(CONNECTION_TIMEOUT_MS)
      .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
      .setSocketTimeout(CONNECTION_TIMEOUT_MS)
      .build();
  HttpPost request = new HttpPost(uri);
  request.setConfig(config);
  request.addHeader("Content-Type", "application/json");
  request.setEntity(new StringEntity(payload));
  CloseableHttpResponse response = client.execute(request);
  if (response.getStatusLine().getStatusCode() >= 300) {
    throw new MininetException(String.format("failure - received a %d for %s.", 
        response.getStatusLine().getStatusCode(), request.getURI().toString()));
  }
  return response;
}
项目:java-web-services-training    文件:Jws1042Application.java   
public static void main(String[] args) throws IOException, URISyntaxException {
    ObjectMapper mapper = new ObjectMapper();
    try (CloseableHttpClient client =
                 HttpClientBuilder.create().useSystemProperties().build()) {
        URI uri = new URIBuilder("http://api.geonames.org/searchJSON")
                .addParameter("q", "kabupaten garut")
                .addParameter("username", "ceefour")
                .build();
        HttpGet getRequest = new HttpGet(uri);
        try (CloseableHttpResponse resp = client.execute(getRequest)) {
            String body = IOUtils.toString(resp.getEntity().getContent(),
                    StandardCharsets.UTF_8);
            JsonNode bodyNode = mapper.readTree(body);
            LOG.info("Status: {}", resp.getStatusLine());
            LOG.info("Headers: {}", resp.getAllHeaders());
            LOG.info("Body: {}", body);
            LOG.info("Body (JsonNode): {}", bodyNode);
            for (JsonNode child : bodyNode.get("geonames")) {
                LOG.info("Place: {} ({}, {})", child.get("toponymName"), child.get("lat"), child.get("lng"));
            }
        }
    }
}
项目:bandcamp-api    文件:ConfigUtil.java   
public static String buildAPICall(APICall query, Map<String, String> parameters) throws Exception
{
    if(query != null && StringUtils.isNotBlank(query.getBaseURL()))
    {
        logger.debug("APICall Base URL: " + query.getBaseURL());
        URIBuilder builder = new URIBuilder(query.getBaseURL());
        if(parameters != null && !parameters.isEmpty() && query.HasParameters())
        {
            for (Map.Entry<String, String> entry : parameters.entrySet())
            {
                String key = entry.getKey();
                if(StringUtils.isNotBlank(key) && query.getParameters().contains(key))
                {
                    String value = entry.getValue();
                    builder.addParameter(key, value);
                    logger.debug("Added Parameter: key=" + key + ", value=" + value);
                }
            }
        }

        return builder.build().toString();
    }
    return null;
}
项目:incubator-servicecomb-java-chassis    文件:RegistryUtils.java   
/**
 * 对于配置为0.0.0.0的地址,通过查询网卡地址,转换为实际监听的地址。
 */
public static String getPublishAddress(String schema, String address) {
  if (address == null) {
    return address;
  }

  try {
    URI originalURI = new URI(schema + "://" + address);
    IpPort ipPort = NetUtils.parseIpPort(originalURI.getAuthority());
    if (ipPort == null) {
      LOGGER.warn("address {} not valid.", address);
      return null;
    }

    IpPort publishIpPort = genPublishIpPort(schema, ipPort);
    URIBuilder builder = new URIBuilder(originalURI);
    return builder.setHost(publishIpPort.getHostOrIp()).setPort(publishIpPort.getPort()).build().toString();
  } catch (URISyntaxException e) {
    LOGGER.warn("address {} not valid.", address);
    return null;
  }
}
项目:mxhsd    文件:HttpFederationClient.java   
private JsonObject sendPut(URIBuilder target, JsonObject payload) {
    try {
        if (!target.getScheme().equals("matrix")) {
            throw new IllegalArgumentException("Scheme can only be matrix");
        }

        String domain = target.getHost();
        target.setScheme("https");
        IRemoteAddress addr = resolver.resolve(target.getHost());
        target.setHost(addr.getHost());
        target.setPort(addr.getPort());

        return sendPut(domain, target.build(), payload);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
项目:NGB-master    文件:DatasetListHandler.java   
private HttpRequestBase createTreeRequest(Long parentId) {
    try {
        URIBuilder builder = new URIBuilder(serverParameters.getServerUrl()
                + serverParameters.getProjectTreeUrl());
        builder.addParameter("parentId", String.valueOf(parentId));

        HttpGet get = new HttpGet(builder.build());
        setDefaultHeader(get);
        if (isSecure()) {
            addAuthorizationToRequest(get);
        }
        return get;
    } catch (URISyntaxException e) {
        throw new ApplicationException(e.getMessage(), e);
    }
}
项目:IPPR2016    文件:ProcessEngineCallerImpl.java   
@Async
public Future<ProcessStateDTO> getProcessState(final Long piId) throws URISyntaxException {
  final CompletableFuture<ProcessStateDTO> future = new CompletableFuture<>();

  final URIBuilder uri =
      new URIBuilder(gatewayConfig.getProcessEngineAddress()).setPath("processes/state/" + piId);

  final ListenableFuture<ResponseEntity<ProcessStateDTO>> responseFuture =
      createRequest(uri, HttpMethod.GET, null, ProcessStateDTO.class, null);

  responseFuture.addCallback(result -> {
    final List<UserContainer> container = Lists.newArrayList(result.getBody().getSubjects());
    getUser(container);
    future.complete(result.getBody());
  }, error -> {
    future.completeExceptionally(error);
  });

  return future;
}
项目:sjk    文件:CatalogConvertorControllerTest.java   
@Test
public void testEdit() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.json";
    URIBuilder urlb = new URIBuilder(url);

    // 参数
    urlb.setParameter("id", "1");
    urlb.setParameter("marketName", "eoemarket");
    urlb.setParameter("catalog", "1");
    urlb.setParameter("subCatalog", "15");
    urlb.setParameter("subCatalogName", "系统工具1");
    urlb.setParameter("targetCatalog", "1");
    urlb.setParameter("targetSubCatalog", "14");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
项目:NGB-master    文件:AbstractHTTPCommandHandler.java   
private BiologicalDataItem loadFileByBioID(String id) {
    try {
        URI uri = new URIBuilder(serverParameters.getServerUrl() + serverParameters.getFileFindUrl())
                .addParameter("id", id)
                .build();
        HttpGet get = new HttpGet(uri);
        setDefaultHeader(get);
        String result = RequestManager.executeRequest(get);
        ResponseResult<BiologicalDataItem> responseResult = getMapper().readValue(result,
                getMapper().getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                        BiologicalDataItem.class));
        if (responseResult == null || responseResult.getPayload() == null) {
            throw new ApplicationException("Failed to find a file by Bio item ID: " + id + ".");
        }
        return responseResult.getPayload();
    } catch (IOException | URISyntaxException e) {
        throw new ApplicationException("", e);
    }
}
项目:NGB-master    文件:DatasetRegistrationHandler.java   
/**
 * Performs a dataset registration request to NGB server and prints registration result to
 * StdOut if it is specified by the command line options
 * @return 0 if request completed successfully
 */
@Override public int runCommand() {
    try {
        URIBuilder builder = new URIBuilder(serverParameters.getServerUrl() + getRequestUrl());
        if (parentId != null) {
            builder.addParameter("parentId", String.valueOf(parentId));
        }
        HttpPost post = new HttpPost(builder.build());
        setDefaultHeader(post);
        if (isSecure()) {
            addAuthorizationToRequest(post);
        }
        RegistrationRequest registration = new RegistrationRequest();
        registration.setName(name);
        registration.setItems(items);
        String result = getPostResult(registration, post);
        checkAndPrintDatasetResult(result, printJson, printTable);
    } catch (URISyntaxException e) {
        throw new ApplicationException(e.getMessage(), e);
    }
    return 0;
}
项目:mxisd    文件:ClientDnsOverwrite.java   
public URIBuilder transform(URI initial) {
    URIBuilder builder = new URIBuilder(initial);
    Entry mapping = mappings.get(initial.getHost());
    if (mapping == null) {
        return builder;
    }

    try {
        URL target = new URL(mapping.getValue());
        builder.setScheme(target.getProtocol());
        builder.setHost(target.getHost());
        if (target.getPort() != -1) {
            builder.setPort(target.getPort());
        }

        return builder;
    } catch (MalformedURLException e) {
        log.warn("Skipping DNS overwrite entry {} due to invalid value [{}]: {}", mapping.getName(), mapping.getValue(), e.getMessage());
        throw new ConfigurationException("Invalid DNS overwrite entry in homeserver client: " + mapping.getName(), e.getMessage());
    }
}
项目:kafka-connect-marklogic    文件:MarkLogicWriter.java   
/**
 * 
 * @param payload
 * @return
 */
protected HttpPut createPutRequest(final Object value, final String collection) {

    try {
        logger.debug("received value {}, and collection {}", value, collection);
        final Map<?, ?> valueMap = new LinkedHashMap<>((Map<?,?>)value);
        final Object url = valueMap.remove(URL);
        final URIBuilder uriBuilder = getURIBuilder(null == url ? UUID.randomUUID().toString() : url.toString(), collection);
        final String jsonString = MAPPER.writeValueAsString(valueMap);
        final HttpPut request = new HttpPut(uriBuilder.build());
        final StringEntity params = new StringEntity(jsonString, "UTF-8");
        params.setContentType(DEFAULT_CONTENT_TYPE.toString());
        request.setEntity(params);
        return request;
    } catch (URISyntaxException | JsonProcessingException | MalformedURLException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    } 
}
项目:url-to-google-drive    文件:GoogleOauthController.java   
private User getUser(@NotNull Token token) throws IOException, URISyntaxException {

        URIBuilder builder = new URIBuilder(PROFILE_URL);
        builder.addParameter("access_token", token.getAccessToken());

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(builder.build());
        org.apache.http.HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        InputStream inputStream = response.getEntity().getContent();

        if (HttpUtilities.success(statusCode)) {
            User user = gson.fromJson(new InputStreamReader(inputStream), User.class);
            user.setToken(token);
            return user;
        }

        throw new ApiException(HttpStatus.valueOf(statusCode));
    }
项目:NGB-master    文件:AbstractHTTPCommandHandler.java   
/**
 * Finds files on the NGB server with a name matching input query.
 * @param strId query to find
 * @param strict determines type of search, if true a strict equality by name search is performed
 *               otherwise a substring case-insensitive search is done
 * @return list of files matching a query
 */
protected List<BiologicalDataItem> loadItemsByName(String strId, boolean strict) {
    try {
        URI uri = new URIBuilder(serverParameters.getServerUrl() + serverParameters.getSearchUrl())
                .addParameter("name", strId)
                .addParameter("strict", String.valueOf(strict))
                .build();
        HttpGet get = new HttpGet(uri);
        setDefaultHeader(get);
        String result = RequestManager.executeRequest(get);
        ResponseResult<List<BiologicalDataItem>> responseResult = getMapper().readValue(result,
                getMapper().getTypeFactory().constructParametrizedType(
                        ResponseResult.class, ResponseResult.class,
                        getMapper().getTypeFactory().constructParametrizedType(
                                List.class, List.class, BiologicalDataItem.class)));
        if (responseResult == null) {
            throw new ApplicationException(getMessage(ERROR_FILE_NOT_FOUND, strId));
        }
        return responseResult.getPayload();
    } catch (IOException | URISyntaxException e) {
        throw new ApplicationException(e.getMessage(), e);
    }
}
项目:devops-cstack    文件:SimpleDockerDriver.java   
@Override
public DockerResponse findAll() throws FatalDockerJSONException {
    URI uri = null;
    String body = new String();
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host).setPath("/containers/json").build();
        dockerResponse = client.sendGet(uri);
    } catch (URISyntaxException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("request body : " + body + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException(
                "An error has occurred for find all containers request due to " + e.getMessage(), e);
    }

    return dockerResponse;
}
项目:devops-cstack    文件:SimpleDockerDriver.java   
@Override
public DockerResponse create(DockerContainer container) throws FatalDockerJSONException {
    URI uri = null;
    String body = new String();
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host).setPath("/containers/create")
                .setParameter("name", container.getName()).build();
        body = objectMapper.writeValueAsString(container.getConfig());
        dockerResponse = client.sendPost(uri, body, "application/json");
    } catch (URISyntaxException | IOException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("request body : " + body + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException(
                "An error has occurred for create container request due to " + e.getMessage(), e);
    }
    return dockerResponse;
}
项目:devops-cstack    文件:SimpleDockerDriver.java   
@Override
public DockerResponse stop(DockerContainer container) throws FatalDockerJSONException {
    URI uri = null;
    String body = new String();
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host)
                .setPath("/containers/" + container.getName() + "/stop").setParameter("t", "10").build();
        dockerResponse = client.sendPost(uri, body, "application/json");
    } catch (URISyntaxException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("request body : " + body + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException(
                "An error has occurred for stop container request due to " + e.getMessage(), e);
    }
    return dockerResponse;
}
项目:devops-cstack    文件:SimpleDockerDriver.java   
@Override
public DockerResponse kill(DockerContainer container) throws FatalDockerJSONException {
    URI uri = null;
    String body = new String();
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host)
                .setPath("/containers/" + container.getName() + "/kill").build();
        dockerResponse = client.sendPost(uri, "", "application/json");
    } catch (URISyntaxException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("request body : " + body + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException(
                "An error has occurred for kill container request due to " + e.getMessage(), e);
    }
    return dockerResponse;
}
项目:devops-cstack    文件:SimpleDockerDriver.java   
@Override
public DockerResponse remove(DockerContainer container) throws FatalDockerJSONException {
    URI uri = null;
    String body = new String();
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host).setPath("/containers/" + container.getName())
                .setParameter("v", "1").setParameter("force", "true").build();
        dockerResponse = client.sendDelete(uri, false);
    } catch (URISyntaxException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("request body : " + body + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException("An error has occurred for remove request due to " + e.getMessage(), e);
    }
    return dockerResponse;
}
项目:devops-cstack    文件:SimpleDockerDriver.java   
@Override
public DockerResponse pull(String tag, String repository) throws FatalDockerJSONException {
    URI uri = null;
    String body = new String();
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host).setPath("/images/create")
                .setParameter("fromImage", repository).setParameter("tag", tag.toLowerCase()).build();
        dockerResponse = client.sendPostToRegistryHost(uri, "", "application/json");
        dockerResponse = client.sendPost(uri, "", "application/json");
    } catch (URISyntaxException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("request body : " + body + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException("An error has occurred for pull request due to " + e.getMessage(), e);
    }
    return dockerResponse;
}
项目:groupsio-api-java    文件:GroupResource.java   
/**
 * Gets a {@link Group} for the specified group ID
 * 
 * @return the {@link Group} for the specified group ID
 * @throws URISyntaxException
 * @throws IOException
 * @throws GroupsIOApiException
 */
public Group getGroup(final Integer groupId) throws URISyntaxException, IOException, GroupsIOApiException
{
    if (apiClient.group().getPermissions(groupId).getManageGroupSettings())
    {
        final URIBuilder uri = new URIBuilder().setPath(baseUrl + "getgroup");
        uri.setParameter("group_id", groupId.toString());
        final HttpRequestBase request = new HttpGet();
        request.setURI(uri.build());

        return callApi(request, Group.class);
    }
    else
    {
        final Error error = new Error();
        error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS);
        throw new GroupsIOApiException(error);
    }
}
项目:devops-cstack    文件:SimpleDockerDriver.java   
@Override
public DockerResponse createVolume(Volume volume) throws FatalDockerJSONException {
    URI uri = null;
    String body = new String();
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host).setPath("/volumes/create").build();
        body = objectMapper.writeValueAsString(volume);
        dockerResponse = client.sendPost(uri, body, "application/json");
    } catch (URISyntaxException | IOException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("request body : " + body + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException(
                "An error has occurred for create container request due to " + e.getMessage(), e);
    }
    return dockerResponse;
}
项目:devops-cstack    文件:SimpleDockerDriver.java   
@Override
public DockerResponse findNetwork(Network network) throws FatalDockerJSONException {
    URI uri = null;
    DockerResponse dockerResponse = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host).setPath("/networks/" + network.getId()).build();
        dockerResponse = client.sendGet(uri);
    } catch (URISyntaxException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException(
                "An error has occurred for create container request due to " + e.getMessage(), e);
    }
    return dockerResponse;
}
项目:devops-cstack    文件:SimpleDockerDriver.java   
@Override
public DockerResponse connectToNetwork(Network network, String containerId) throws FatalDockerJSONException {
    URI uri = null;
    DockerResponse dockerResponse = null;
    String body = null;
    try {
        uri = new URIBuilder().setScheme(NamingUtils.getProtocolSocket(isUnixSocket, mode)).setHost(host).setPath("/networks/" + network.getId() + "/connect").build();
        body = "{ \"Container\":\"" + containerId + "\" }";
        dockerResponse = client.sendPost(uri, body, "application/json");
    } catch (URISyntaxException | JSONClientException e) {
        StringBuilder contextError = new StringBuilder(256);
        contextError.append("uri : " + uri + " - ");
        contextError.append("server response : " + dockerResponse);
        logger.error(contextError.toString());
        throw new FatalDockerJSONException(
                "An error has occurred for create container request due to " + e.getMessage(), e);
    }
    return dockerResponse;
}
项目:groupsio-api-java    文件:UserResource.java   
/**
 * Gets a list of {@link Subscription}s that the current user is subscribed
 * to.
 * 
 * @return {@link List}<{@link Subscription}> representing the subscriptions
 * @throws URISyntaxException
 * @throws IOException
 * @throws GroupsIOApiException
 */
public List<Subscription> getSubscriptions() throws URISyntaxException, IOException, GroupsIOApiException
{
    final URIBuilder uri = new URIBuilder().setPath(baseUrl + "getsubs");
    uri.setParameter("limit", MAX_RESULTS);
    final HttpGet request = new HttpGet();
    request.setURI(uri.build());

    Page page = callApi(request, Page.class);

    final List<Subscription> subscriptions = Arrays.asList(OM.convertValue(page.getData(), Subscription[].class));

    while (page.getHasMore())
    {
        uri.setParameter("page_token", page.getNextPageToken().toString());
        request.setURI(uri.build());
        page = callApi(request, Page.class);
        subscriptions.addAll(Arrays.asList(OM.convertValue(page.getData(), Subscription[].class)));
    }

    return subscriptions;
}
项目:nextcloud-java-api    文件:ConnectorCommon.java   
private URI buildUrl(String subPath, List<NameValuePair> queryParams)
{
    URIBuilder uB= new URIBuilder()
    .setScheme(serverConfig.isUseHTTPS() ? "https" : "http")
    .setHost(serverConfig.getServerName())
    .setUserInfo(serverConfig.getUserName(), serverConfig.getPassword())
    .setPath(subPath);
    if (queryParams != null)
    {
        uB.addParameters(queryParams);
    }
    try {
        return uB.build();
    } catch (URISyntaxException e) {
        throw new NextcloudApiException(e);
    }
}
项目:para-search-elasticsearch    文件:ProxyResourceHandler.java   
String getCleanPath(String path) {
    if (StringUtils.containsIgnoreCase(path, "getRawResponse")) {
        try {
            URIBuilder uri = new URIBuilder(path);
            List<NameValuePair> params = uri.getQueryParams();
            for (Iterator<NameValuePair> iterator = params.iterator(); iterator.hasNext();) {
                NameValuePair next = iterator.next();
                if (next.getName().equalsIgnoreCase("getRawResponse")) {
                    iterator.remove();
                    break;
                }
            }
            path = uri.setParameters(params).toString();
        } catch (URISyntaxException ex) {
            logger.warn(null, ex);
        }
    }
    return StringUtils.isBlank(path) ? "_search" : path;
}
项目:sjk    文件:CatalogConvertorControllerTest.java   
@Test
public void testEditList() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.list.d";
    URIBuilder urlb = new URIBuilder(url);

    // 参数
    urlb.setParameter("id", "1,2");
    urlb.setParameter("marketName", "eoemarket,eoemarket");
    urlb.setParameter("catalog", "1,1");
    urlb.setParameter("subCatalog", "15,8");
    urlb.setParameter("subCatalogName", "系统工具,生活娱乐1");
    urlb.setParameter("targetCatalog", "1,1");
    urlb.setParameter("targetSubCatalog", "14,9");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
项目:NGB-master    文件:AbstractHTTPCommandHandler.java   
private Project loadProjectByName(String strId) {
    try {
        URI uri = new URIBuilder(serverParameters.getServerUrl() + serverParameters.getProjectLoadUrl())
                .addParameter("projectName", strId)
                .build();
        HttpGet get = new HttpGet(uri);
        setDefaultHeader(get);
        String result = RequestManager.executeRequest(get);
        ResponseResult<Project> responseResult = getMapper().readValue(result,
                getMapper().getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class,
                        Project.class));
        if (responseResult == null || responseResult.getPayload() == null) {
            throw new ApplicationException("Failed to find a project by name: " + strId + ".");
        }
        return responseResult.getPayload();
    } catch (IOException | URISyntaxException e) {
        throw new ApplicationException("", e);
    }
}
项目:CurseSync    文件:SafeRedirectStrategy.java   
@Override
protected URI createLocationURI(String location) throws ProtocolException
{
    try
    {
        final URIBuilder b = new URIBuilder(new URI(encode(location)).normalize());
        final String host = b.getHost();
        if (host != null)
        {
            b.setHost(host.toLowerCase(Locale.ROOT));
        }
        final String path = b.getPath();
        if (TextUtils.isEmpty(path))
        {
            b.setPath("/");
        }
        return b.build();
    }
    catch (final URISyntaxException ex)
    {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }
}
项目:graphouse    文件:ClickHouseStatementImpl.java   
URI buildRequestUri(
    String sql,
    List<ClickHouseExternalData> externalData,
    Map<ClickHouseQueryParam, String> additionalClickHouseDBParams,
    boolean ignoreDatabase
) {
    try {
        List<NameValuePair> queryParams = getUrlQueryParams(
            sql,
            externalData,
            additionalClickHouseDBParams,
            ignoreDatabase
        );

        return new URIBuilder()
            .setScheme("http")
            .setHost(properties.getHost())
            .setPort(properties.getPort())
            .setPath("/")
            .setParameters(queryParams)
            .build();
    } catch (URISyntaxException e) {
        log.error("Mailformed URL: " + e.getMessage());
        throw new IllegalStateException("illegal configuration of db");
    }
}
项目:groupsio-api-java    文件:MemberResource.java   
/**
 * Gets a user's {@link Subscription} for the specified group and member IDs
 * 
 * @return the user's {@link Subscription} for the specified group ID
 * @throws URISyntaxException
 * @throws IOException
 * @throws GroupsIOApiException
 */
public Subscription getMemberInGroup(final Integer groupId, final Integer memberId)
        throws URISyntaxException, IOException, GroupsIOApiException
{
    if (apiClient.group().getPermissions(groupId).getViewMembers())
    {
        final URIBuilder uri = new URIBuilder().setPath(baseUrl + "getmember");
        uri.setParameter("group_id", groupId.toString());
        uri.setParameter("sub_id", memberId.toString());
        final HttpRequestBase request = new HttpGet();
        request.setURI(uri.build());

        return callApi(request, Subscription.class);
    }
    else
    {
        final Error error = new Error();
        error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS);
        throw new GroupsIOApiException(error);
    }
}
项目:groupsio-api-java    文件:MemberResource.java   
/**
 * Ban a member if they aren't already banned
 * 
 * @param groupId
 *            of the group they belong to
 * @param subscriptionId
 *            of the subscription they have
 * @return the user's {@link Subscription}
 * @throws URISyntaxException
 * @throws IOException
 * @throws GroupsIOApiException
 */
public Subscription banMember(final Integer groupId, final Integer subscriptionId)
        throws URISyntaxException, IOException, GroupsIOApiException
{
    if (apiClient.group().getPermissions(groupId).getBanMembers()
            && getMemberInGroup(groupId, subscriptionId).getStatus().canBan())
    {
        final URIBuilder uri = new URIBuilder().setPath(baseUrl + "banmember");
        uri.setParameter("group_id", groupId.toString());
        uri.setParameter("sub_id", subscriptionId.toString());
        final HttpRequestBase request = new HttpGet();
        request.setURI(uri.build());

        return callApi(request, Subscription.class);
    }
    else
    {
        final Error error = new Error();
        error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS);
        throw new GroupsIOApiException(error);
    }
}
项目:dooo    文件:HttpServiceRequest.java   
private URI buildURI() {
    try {
        URIBuilder builder = new URIBuilder(httpServiceInfo.getUrl()).setCharset(CHARSET);
        for (Map.Entry<String, String> param : parameters.entrySet()) {
            String value = param.getValue();
            if (value == null || Constants.JSON_BODY.equals(param.getKey())) {
                continue;
            }
            builder.addParameter(param.getKey(), value);
        }
        return builder.build();
    } catch (URISyntaxException e) {
        LOGGER.error("", e);
        throw new RuntimeException(e);
    }
}
项目:groupsio-api-java    文件:MemberResource.java   
/**
 * Add members directly to a group
 *
 * @param groupId
 *      of the group they should be added to
 * @param emails
 *      a list of email address to add.
 * @throws URISyntaxException
 * @throws IOException
 * @throws GroupsIOApiException
 */
public void directAddMember(final Integer groupId, List<String> emails)
        throws URISyntaxException, IOException, GroupsIOApiException
{

    if (apiClient.group().getPermissions(groupId).getInviteMembers())
    {
        final URIBuilder uri = new URIBuilder().setPath(baseUrl + "directadd");
        uri.setParameter("group_id", groupId.toString());
        uri.setParameter("emails", String.join("\n", emails));
        final HttpRequestBase request = new HttpGet();
        request.setURI(uri.build());

        callApi(request, DirectAdd.class);
    }
    else
    {
        final Error error = new Error();
        error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS);
        throw new GroupsIOApiException(error);
    }
}
项目:groupsio-api-java    文件:MemberResource.java   
/**
 * Remove a member from a group
 * 
 * @param groupId
 *            of the group they belong to
 * @param subscriptionId
 *            of the subscription they have
 * @return the user's {@link Subscription}
 * @throws URISyntaxException
 * @throws IOException
 * @throws GroupsIOApiException
 */
public Subscription removeMember(final Integer groupId, final Integer subscriptionId)
        throws URISyntaxException, IOException, GroupsIOApiException
{
    if (apiClient.group().getPermissions(groupId).getRemoveMembers())
    {
        final URIBuilder uri = new URIBuilder().setPath(baseUrl + "removemember");
        uri.setParameter("group_id", groupId.toString());
        uri.setParameter("sub_id", subscriptionId.toString());
        final HttpRequestBase request = new HttpGet();
        request.setURI(uri.build());

        return callApi(request, Subscription.class);
    }
    else
    {
        final Error error = new Error();
        error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS);
        throw new GroupsIOApiException(error);
    }
}
项目:jeeves    文件:WechatHttpServiceInternal.java   
VerifyUserResponse acceptFriend(String hostUrl, BaseRequest baseRequest, String passTicket, VerifyUser[] verifyUsers) throws IOException, URISyntaxException {
    final int opCode = VerifyUserOPCode.VERIFYOK.getCode();
    final int[] sceneList = new int[]{AddScene.WEB.getCode()};
    final String path = String.format(WECHAT_URL_VERIFY_USER, hostUrl);
    VerifyUserRequest request = new VerifyUserRequest();
    request.setBaseRequest(baseRequest);
    request.setOpcode(opCode);
    request.setSceneList(sceneList);
    request.setSceneListCount(sceneList.length);
    request.setSkey(baseRequest.getSkey());
    request.setVerifyContent("");
    request.setVerifyUserList(verifyUsers);
    request.setVerifyUserListSize(verifyUsers.length);

    URIBuilder builder = new URIBuilder(path);
    builder.addParameter("r", String.valueOf(System.currentTimeMillis()));
    builder.addParameter("pass_ticket", passTicket);
    final URI uri = builder.build().toURL().toURI();

    ResponseEntity<String> responseEntity
            = restTemplate.exchange(uri, HttpMethod.POST, new HttpEntity<>(request, this.postHeader), String.class);
    return jsonMapper.readValue(WechatUtils.textDecode(responseEntity.getBody()), VerifyUserResponse.class);
}
项目:sjk    文件:AccessEoemarketDaoImpl.java   
public PaginationMarketApp getPagination(String url, int currentPage, String key, int maxrow) throws Exception {
    URIBuilder builder = new URIBuilder(url);
    builder.setParameter("currentPage", String.valueOf(currentPage));
    builder.setParameter("key", key);
    builder.setParameter("maxrow", String.valueOf(maxrow));
    return getMarketAppForFull(builder);
}
项目:sjk    文件:MarketControllerTest.java   
@Test
public void testBrokenLink() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/market/brokenLink.d";
    URIBuilder urlb = new URIBuilder(url);
    String test = "";
    urlb.setParameter("c", test);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httPost);
    logger.debug("URL:{}\n{}\n", url, response.getStatusLine());
}