下面列出了怎么用org.apache.http.client.utils.URIBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
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));
}
public String getMethodNameForId(String apiId, String methodId) throws AppException {
ObjectMapper mapper = new ObjectMapper();
String response = null;
URI uri;
try {
uri = new URIBuilder(CommandParameters.getInstance().getAPIManagerURL()).setPath(RestAPICall.API_VERSION + "/proxies/"+apiId+"/operations/"+methodId).build();
RestAPICall getRequest = new GETRequest(uri, null);
HttpResponse httpResponse = getRequest.execute();
response = EntityUtils.toString(httpResponse.getEntity());
EntityUtils.consume(httpResponse.getEntity());
LOG.trace("Response: " + response);
JsonNode operationDetails = mapper.readTree(response);
if(operationDetails.size()==0) {
LOG.warn("No operation with ID: "+methodId+" found for API with id: " + apiId);
return null;
}
return operationDetails.get("name").asText();
} catch (Exception e) {
LOG.error("Can't load name for operation with id: "+methodId+" for API: "+apiId+". Can't parse response: " + response);
throw new AppException("Can't load name for operation with id: "+methodId+" for API: "+apiId, ErrorCode.API_MANAGER_COMMUNICATION, e);
}
}
@Test
public void upload1 () throws URISyntaxException, IOException
{
final ChannelTester tester = getTester ();
final File file = getAbsolutePath ( CommonResources.BUNDLE_1_RESOURCE );
final URIBuilder b = new URIBuilder ( resolve ( "/api/v2/upload/channel/%s/%s", tester.getId (), file.getName () ) );
b.setUserInfo ( "deploy", this.deployKey );
b.addParameter ( "foo:bar", "baz" );
try ( final CloseableHttpResponse response = upload ( b, file ) )
{
Assert.assertEquals ( 200, response.getStatusLine ().getStatusCode () );
}
final Set<String> arts = tester.getAllArtifactIds ();
Assert.assertEquals ( 1, arts.size () );
}
private URI buildUrl(String subPath, List<NameValuePair> queryParams)
{
if(serverConfig.getSubpathPrefix()!=null) {
subPath = serverConfig.getSubpathPrefix()+"/"+subPath;
}
URIBuilder uB= new URIBuilder()
.setScheme(serverConfig.isUseHTTPS() ? "https" : "http")
.setHost(serverConfig.getServerName())
.setPort(serverConfig.getPort())
.setUserInfo(serverConfig.getUserName(), serverConfig.getPassword())
.setPath(subPath);
if (queryParams != null)
{
uB.addParameters(queryParams);
}
try {
return uB.build();
} catch (URISyntaxException e) {
throw new NextcloudApiException(e);
}
}
public void updateRetirementDate(APIChangeState changeState) throws AppException {
if(changeState!=null && changeState.getNonBreakingChanges().contains("retirementDate")) {
// Ignore the retirementDate if desiredState is not deprecated as it's used nowhere
if(!desiredState.getState().equals(IAPI.STATE_DEPRECATED)) {
LOG.info("Ignoring given retirementDate as API-Status is not set to deprecated");
return;
}
try {
URI uri = new URIBuilder(cmd.getAPIManagerURL())
.setPath(RestAPICall.API_VERSION+"/proxies/"+actualState.getId()+"/deprecate").build();
RestAPICall apiCall = new POSTRequest(new StringEntity("retirementDate="+formatRetirementDate(desiredState.getRetirementDate())), uri, this, true);
apiCall.setContentType("application/x-www-form-urlencoded");
apiCall.execute();
} catch (Exception e) {
ErrorState.getInstance().setError("Error while updating the retirementDate.", ErrorCode.CANT_UPDATE_API_PROXY);
throw new AppException("Error while updating the retirementDate", ErrorCode.CANT_UPDATE_API_PROXY);
}
}
return;
}
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;
}
@Override
public void validate(ConfigProblemSetBuilder p, PublicService n) {
String overrideBaseUrl = n.getOverrideBaseUrl();
if (!StringUtils.isEmpty(overrideBaseUrl)) {
try {
URI uri = new URIBuilder(overrideBaseUrl).build();
if (StringUtils.isEmpty(uri.getScheme())) {
p.addProblem(ERROR, "You must supply a URI scheme, e.g. 'http://' or 'https://'");
}
if (StringUtils.isEmpty(uri.getHost())) {
p.addProblem(ERROR, "You must supply a URI host");
}
} catch (URISyntaxException e) {
p.addProblem(ERROR, "Invalid base URL: " + e.getMessage());
}
}
}
@Override
public AsyncExecutionResult generateResultUrl(Object... args) {
// check pre-condition
Validate.notNull(args);
Validate.isTrue(args.length == 2);
Validate.isInstanceOf(String.class, args[0]);
Validate.isInstanceOf(String.class, args[1]);
String preparationId = (String) args[0];
String headId = (String) args[1];
URIBuilder builder = new URIBuilder();
builder.setPath("/api/preparations/" + preparationId + "/metadata");
if (StringUtils.isNotEmpty(headId)) {
builder.setParameter("version", headId);
}
return new AsyncExecutionResult(builder.toString());
}
@Test
public void call_get_query_with_special_separator() throws Exception {
wireMockRule.stubFor(
get(urlPathEqualTo("/team/my_team"))
.willReturn(
ok()
.withBody("{{request.query.q}}")
.withTransformers("response-template")));
String query = "from:2016-01-01;to:2016-01-31";
URI target = new URIBuilder("http://localhost:8082/test/my_team")
.addParameter("id", "20000047")
.addParameter("idType", "1")
.addParameter("q", query)
.build();
HttpResponse response = Request.Get(target).execute().returnResponse();
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
String responseContent = StringUtils.copy(response.getEntity().getContent());
assertEquals(query, responseContent);
wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/team/my_team")));
}
@Test
public void getCertificateTest() throws Exception {
URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.addHeader("Accept", "application/json");
CloseableHttpResponse response1 = httpClient.execute(httpGet);
assertEquals(200, response1.getStatusLine().getStatusCode());
try {
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
response1.close();
}
}
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();
}
HttpPost getHttpMethod( String vURLService ) throws URISyntaxException {
URIBuilder uriBuilder = new URIBuilder( vURLService );
HttpPost vHttpMethod = new HttpPost( uriBuilder.build() );
vHttpMethod.setHeader( "Content-Type", "text/xml;charset=UTF-8" );
String soapAction = "\"" + meta.getOperationNamespace();
if ( !meta.getOperationNamespace().endsWith( "/" ) ) {
soapAction += "/";
}
soapAction += meta.getOperationName() + "\"";
logDetailed( BaseMessages.getString( PKG, "WebServices.Log.UsingRequestHeaderSOAPAction", soapAction ) );
vHttpMethod.setHeader( "SOAPAction", soapAction );
return vHttpMethod;
}
public boolean terminateInstance(String instanceId) {
try {
if (log.isDebugEnabled()) {
log.debug(String.format("Terminate instance: [instance-id] %s", instanceId));
}
URI uri = new URIBuilder(endpoint + INSTANCES_CONTEXT + instanceId).build();
org.apache.stratos.mock.iaas.client.rest.HttpResponse response = doDelete(uri);
if (response != null) {
if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) {
return true;
} else {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
org.apache.stratos.mock.iaas.domain.ErrorResponse errorResponse = gson
.fromJson(response.getContent(), org.apache.stratos.mock.iaas.domain.ErrorResponse.class);
if (errorResponse != null) {
throw new RuntimeException(errorResponse.getErrorMessage());
}
}
}
throw new RuntimeException("An unknown error occurred");
} catch (Exception e) {
String message = "Could not start mock instance";
throw new RuntimeException(message, e);
}
}
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));
}
public JsonNode listTasks(ServerConfig serverConfig, ObjectNode bodyNode) {
JsonNode resultNode = null;
try {
URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_TASK_QUERY_URL);
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;
}
public HttpRequestBuilder withPath(String path) {
try {
URIBuilder uri = new URIBuilder(path);
request.setServerName("test.host");
request.setContextPath(CONTEXT_PATH);
request.setParameters(splitQuery(uri));
request.setRequestURI(CONTEXT_PATH + uri.getPath());
request.setServletPath(uri.getPath());
if (!uri.getQueryParams().isEmpty()) {
request.setQueryString(URLEncodedUtils.format(uri.getQueryParams(), UTF_8));
}
return this;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@NotNull
public URI buildUri(String path, NameValuePair... parameters) throws URISyntaxException {
HttpHost targetHost = httpClientContext.getTargetHost();
return new URIBuilder()
.setHost(targetHost.getHostName())
.setPort(targetHost.getPort())
.setScheme(targetHost.getSchemeName())
.setPath(contextPath + path)
.setParameters(parameters)
.build();
}
private HttpRequestBase onExecute(String id) {
try {
URIBuilder uriBuilder = new URIBuilder(preparationServiceUrl + "/preparations/" + id + "/folder");
return new HttpGet(uriBuilder.build());
} catch (URISyntaxException e) {
throw new TDPException(UNEXPECTED_EXCEPTION, e);
}
}
public JsonNode getVariables(ServerConfig serverConfig, String caseInstanceId) {
URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_VARIABLE_INSTANCE_LIST_URL);
builder.addParameter("caseInstanceId", caseInstanceId);
builder.addParameter("size", DEFAULT_VARIABLE_RESULT_SIZE);
builder.addParameter("sort", "variableName");
HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
return clientUtil.executeRequest(get, serverConfig);
}
@NotNull
public static String planDetailsUrl(@NotNull final String planId) throws Exception {
final URIBuilder uriBuilder = getUriBuilder();
StringBuilder pathString = new StringBuilder()
.append(API)
.append(API_VERSION)
.append(PLAN_DETAILS_PATH)
.append(PATH_SEPARATOR)
.append(planId);
uriBuilder.setPath(pathString.toString());
return uriBuilder.build().toURL().toString();
}
public void start() throws Exception {
Objects.nonNull(config);
assert(config.getScheme().startsWith("http"));
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme(config.getScheme());
uriBuilder.setHost(config.getHosts().get(0));
uriBuilder.setPort(config.getPort().intValue());
baseURI = uriBuilder.build();
client = HttpClients.createDefault();
}
private HttpRequestBase onExecute(final String to, final String from) {
try {
URIBuilder builder = new URIBuilder(preparationServiceUrl + "/preparations/" + to + "/steps/copy");
builder.addParameter("from", from);
return new HttpPut(builder.build());
} catch (URISyntaxException e) {
throw new TDPException(UNEXPECTED_EXCEPTION, e);
}
}
@NotNull
public static String listVariablesUrl() throws Exception {
final URIBuilder uriBuilder = getUriBuilder();
StringBuilder pathString = new StringBuilder()
.append(API)
.append(API_VERSION)
.append(VARIABLE_PATH);
uriBuilder.setPath(pathString.toString());
return uriBuilder.build().toURL().toString();
}
/**
* @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);
}
protected HttpUriRequest createGoodCoAnnotationRequest(int n) throws URISyntaxException {
URIBuilder uriBuilder = new URIBuilder()
.setScheme("http")
.setHost("localhost").setPort(9031)
// .setPath("/owlsim/getCoAnnotationListForAttribute/");
.setPath("/owlsim/getCoAnnotatedClasses/");
List<OWLClass> allClasses = new ArrayList<OWLClass>();
allClasses.addAll(g.getAllOWLClasses());
Collections.shuffle(allClasses);
int i=0;
/*
for (OWLClass c : allClasses) {
String id = g.getIdentifier(c);
uriBuilder.addParameter("a", id);
i++;
if (i >= n)
break;
} */
// uriBuilder.addParameter("a","HP:0001252");
// uriBuilder.addParameter("a","HP:0001250");
// uriBuilder.addParameter("a","HP:0000252");
uriBuilder.addParameter("a","MP:0002082");
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;
}
public JsonNode getSubTasks(ServerConfig serverConfig, String taskId) {
URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_TASK_LIST_URL);
builder.addParameter("parentTaskId", taskId);
builder.addParameter("size", DEFAULT_SUBTASK_RESULT_SIZE);
HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
return clientUtil.executeRequest(get, serverConfig);
}
public boolean delete(String path) {
log.debug("File Station Delete");
boolean ret = false;
try {
baseUrl = "http://" + settingService.getSettingValue("DS_HOST") + ":"
+ settingService.getSettingValue("DS_PORT") + "/webapi";
URIBuilder builder = new URIBuilder(baseUrl + "/entry.cgi");
builder.setParameter("api", "SYNO.FileStation.Delete").setParameter("version", "2")
.setParameter("method", "start").setParameter("path", path).setParameter("recursive", "true")
.setParameter("_sid", sid);
JSONObject resJson = executeGet(builder);
log.debug(builder.toString());
if (resJson != null) {
log.debug(resJson.toString());
if (resJson.has("success")) {
if (Boolean.parseBoolean(resJson.get("success").toString())) {
ret = true;
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return ret;
}
private URI createDeployUri(String host, String endpoint) {
try {
return new URIBuilder().setScheme("http").setHost(host).setPort(port).setPath(endpoint).build();
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
public DownloadList getInfo(String id) {
log.debug("Download Station getInfo");
DownloadList ret = null;
try {
URIBuilder builder = new URIBuilder(baseUrl + "/DownloadStation/task.cgi");
builder.setParameter("api", "SYNO.DownloadStation.Task").setParameter("version", "3")
.setParameter("method", "getinfo").setParameter("additional", "detail,transfer")
.setParameter("id", id).setParameter("_sid", this.sid);
JSONObject resJson = executeGet(builder);
if(resJson != null) {
if(resJson.has("success")) {
if(Boolean.parseBoolean(resJson.get("success").toString())) {
JSONArray jsonArray = resJson.getJSONObject("data").getJSONArray("tasks");
ret = setInfo(jsonArray.getJSONObject(0));
}
}
}
} catch (URISyntaxException | ParseException | JSONException e) {
log.error(e.getMessage());
}
return ret;
}
public synchronized void commitTransaction() throws RDF4JException, IOException, UnauthorizedException {
checkRepositoryURL();
if (transactionURL == null) {
throw new IllegalStateException("Transaction URL has not been set");
}
HttpPut method = null;
try {
URIBuilder url = new URIBuilder(transactionURL);
url.addParameter(Protocol.ACTION_PARAM_NAME, Action.COMMIT.toString());
method = applyAdditionalHeaders(new HttpPut(url.build()));
final HttpResponse response = execute(method);
try {
int code = response.getStatusLine().getStatusCode();
if (code == HttpURLConnection.HTTP_OK) {
// we're done.
transactionURL = null;
if (ping != null) {
ping.cancel(false);
}
} else {
throw new RepositoryException("unable to commit transaction. HTTP error code " + code);
}
} finally {
EntityUtils.consumeQuietly(response.getEntity());
}
} catch (URISyntaxException e) {
logger.error("could not create URL for transaction commit", e);
throw new RuntimeException(e);
} finally {
if (method != null) {
method.reset();
}
}
}