下面列出了怎么用org.apache.http.client.methods.HttpDelete的API类实例代码及写法,或者点击链接到github查看源代码。
private HttpRequestBase createApacheRequest(HttpExecuteRequest request, String uri) {
switch (request.httpRequest().method()) {
case HEAD:
return new HttpHead(uri);
case GET:
return new HttpGet(uri);
case DELETE:
return new HttpDelete(uri);
case OPTIONS:
return new HttpOptions(uri);
case PATCH:
return wrapEntity(request, new HttpPatch(uri));
case POST:
return wrapEntity(request, new HttpPost(uri));
case PUT:
return wrapEntity(request, new HttpPut(uri));
default:
throw new RuntimeException("Unknown HTTP method name: " + request.httpRequest().method());
}
}
void doDelete(String... path) throws ClientRegistrationException {
try {
HttpDelete request = new HttpDelete(getUrl(baseUri, path));
addAuth(request);
HttpResponse response = httpClient.execute(request);
InputStream responseStream = null;
if (response.getEntity() != null) {
responseStream = response.getEntity().getContent();
}
if (response.getStatusLine().getStatusCode() != 204) {
throw httpErrorException(response, responseStream);
}
} catch (IOException e) {
throw new ClientRegistrationException("Failed to send request", e);
}
}
@Parameters({"admin-username", "admin-password"})
@Test
public void testDeleteQueue(String username, String password) throws IOException {
String queueName = "testDeleteQueue";
// Create a queue to delete.
QueueCreateRequest request = new QueueCreateRequest()
.name(queueName).durable(false).autoDelete(false);
HttpPost httpPost = new HttpPost(apiBasePath + "/queues");
ClientHelper.setAuthHeader(httpPost, username, password);
String value = objectMapper.writeValueAsString(request);
StringEntity stringEntity = new StringEntity(value, ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = client.execute(httpPost);
Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);
// Delete the queue.
HttpDelete httpDelete = new HttpDelete(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH + "/" + queueName);
ClientHelper.setAuthHeader(httpDelete, username, password);
response = client.execute(httpDelete);
Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
}
/**
* Test deleting all local task variables. DELETE runtime/tasks/{taskId}/variables
*/
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/repository/oneHumanTaskCase.cmmn" })
public void testDeleteAllLocalVariables() throws Exception {
// Start process with all types of variables
Map<String, Object> caseVariables = new HashMap<>();
caseVariables.put("var1", "This is a CaseVariable");
CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").variables(caseVariables).start();
// Set local task variables
Task task = taskService.createTaskQuery().caseInstanceId(caseInstance.getId()).singleResult();
Map<String, Object> taskVariables = new HashMap<>();
taskVariables.put("var1", "This is a TaskVariable");
taskVariables.put("var2", 123);
taskService.setVariablesLocal(task.getId(), taskVariables);
assertThat(taskService.getVariablesLocal(task.getId())).hasSize(2);
HttpDelete httpDelete = new HttpDelete(
SERVER_URL_PREFIX + CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
closeResponse(executeBinaryRequest(httpDelete, HttpStatus.SC_NO_CONTENT));
// Check if local variables are gone and global remain unchanged
assertThat(taskService.getVariablesLocal(task.getId())).isEmpty();
assertThat(taskService.getVariables(task.getId())).hasSize(1);
}
/**
* <p>Retrieves the proper extension of {@link HttpRequestBase} for the given {@link InvocationContext}.
* This implementation is solely dependent upon the {@link RequestMethod} property in the annotated
* metdata of the endpoint method definition.</p>
*
* @param context
* the {@link InvocationContext} for which a {@link HttpRequestBase} is to be generated
* <br><br>
* @return the {@link HttpRequestBase} translated from the {@link InvocationContext}'s {@link RequestMethod}
* <br><br>
* @throws NullPointerException
* if the supplied {@link InvocationContext} was {@code null}
* <br><br>
* @since 1.3.0
*/
static HttpRequestBase translateRequestMethod(InvocationContext context) {
RequestMethod requestMethod = Metadata.findMethod(assertNotNull(context).getRequest());
switch (requestMethod) {
case POST: return new HttpPost();
case PUT: return new HttpPut();
case PATCH: return new HttpPatch();
case DELETE: return new HttpDelete();
case HEAD: return new HttpHead();
case TRACE: return new HttpTrace();
case OPTIONS: return new HttpOptions();
case GET: default: return new HttpGet();
}
}
/**
* Deletes the specified stack or a layer of the specified stack.
*
* @param stack stack to delete.
* @param z z value for layer to delete (or null to delete all layers).
*
* @throws IOException
* if the request fails for any reason.
*/
public void deleteStack(final String stack,
final Double z)
throws IOException {
final URI uri;
if (z == null) {
uri = getStackUri(stack);
} else {
uri = getUri(urls.getZUrlString(stack, z));
}
final String requestContext = "DELETE " + uri;
final TextResponseHandler responseHandler = new TextResponseHandler(requestContext);
final HttpDelete httpDelete = new HttpDelete(uri);
LOG.info("deleteStack: submitting {}", requestContext);
httpClient.execute(httpDelete, responseHandler);
}
@Override
public void remove() throws IOException, UnexpectedResponseException {
final UncheckedUriBuilder uri = new UncheckedUriBuilder(
this.baseUri.toString()
);
final HttpDelete delete = new HttpDelete(
uri.build()
);
try {
this.client.execute(
delete,
new MatchStatus(delete.getURI(), HttpStatus.SC_NO_CONTENT)
);
} finally {
delete.releaseConnection();
}
}
/**
* Test deleting a single group.
*/
@Test
public void testDeleteGroup() throws Exception {
try {
Group testGroup = identityService.newGroup("testgroup");
testGroup.setName("Test group");
testGroup.setType("Test type");
identityService.saveGroup(testGroup);
closeResponse(executeRequest(new HttpDelete(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_GROUP, "testgroup")), HttpStatus.SC_NO_CONTENT));
assertThat(identityService.createGroupQuery().groupId("testgroup").singleResult()).isNull();
} finally {
try {
identityService.deleteGroup("testgroup");
} catch (Throwable ignore) {
// Ignore, since the group may not have been created in the test
// or already deleted
}
}
}
public HttpResponse doDelete(String resourcePath) throws RestClientException {
HttpDelete delete = new HttpDelete(resourcePath);
setAuthHeader(delete);
try {
return httpClient.execute(delete);
} catch (IOException e) {
String errorMsg = "Error while executing DELETE statement";
log.error(errorMsg, e);
throw new RestClientException(errorMsg, e);
} finally {
delete.releaseConnection();
}
}
/**
* Test deleting all process variables. DELETE runtime/process-instance/{processInstanceId}/variables
*/
@Test
@Deployment(resources = { "org/flowable/rest/service/api/runtime/ProcessInstanceVariablesCollectionResourceTest.testProcess.bpmn20.xml" })
public void testDeleteAllProcessVariables() throws Exception {
Map<String, Object> processVariables = new HashMap<>();
processVariables.put("var1", "This is a ProcVariable");
processVariables.put("var2", 123);
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess", processVariables);
HttpDelete httpDelete = new HttpDelete(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_VARIABLE_COLLECTION, processInstance.getId()));
closeResponse(executeRequest(httpDelete, HttpStatus.SC_NO_CONTENT));
// Check if local variables are gone and global remain unchanged
assertThat(runtimeService.getVariablesLocal(processInstance.getId())).isEmpty();
}
/**
* Test deleting a single user.
*/
@Test
public void testDeleteUser() throws Exception {
User savedUser = null;
try {
User newUser = identityService.newUser("testuser");
newUser.setFirstName("Fred");
newUser.setLastName("McDonald");
newUser.setEmail("[email protected]");
identityService.saveUser(newUser);
savedUser = newUser;
closeResponse(executeRequest(new HttpDelete(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_USER, newUser.getId())), HttpStatus.SC_NO_CONTENT));
// Check if user is deleted
assertThat(identityService.createUserQuery().userId(newUser.getId()).count()).isZero();
savedUser = null;
} finally {
// Delete user after test fails
if (savedUser != null) {
identityService.deleteUser(savedUser.getId());
}
}
}
@Override
public void doDelete(URI url, HttpServletRequest request, HttpServletResponse response)
throws IOException {
HttpDelete method = new HttpDelete(url);
copyRequestHeaderFields(method, request);
executeRequest(method, request, response);
}
@Test
public void deletePropertyByKey_withValidParameters_sendsDeleteRequestForPropertyKey() throws Exception {
// arrange
CloseableHttpClient httpClientMock = recordHttpClientForSingleResponseWithContentAndStatusCode("", 200);
ConfluenceRestClient confluenceRestClient = new ConfluenceRestClient(CONFLUENCE_ROOT_URL, httpClientMock, null, null);
// act
confluenceRestClient.deletePropertyByKey("1234", "content-hash");
// assert
verify(httpClientMock, times(1)).execute(any(HttpDelete.class));
}
@Test
void shouldFailOnNonBodyRequests() {
final HttpClient client = mock(HttpClient.class);
final StreamingHttpOutputMessage unit = new StreamingApacheClientHttpRequest(client, new HttpDelete());
assertThrows(IllegalStateException.class, () -> unit.setBody(mock(Body.class)));
}
/**
* DELETEメソッド.
* @param url リクエスト対象URL
* @param headers リクエストヘッダのハッシュマップ
* @return DcResponse型
* @throws DcException DAO例外
*/
public final DcResponse del(final String url, final HashMap<String, String> headers) throws DcException {
HttpDelete req = new HttpDelete(url);
for (Map.Entry<String, String> entry : headers.entrySet()) {
req.setHeader(entry.getKey(), entry.getValue());
}
req.addHeader("X-Dc-Version", DcCoreTestConfig.getCoreVersion());
debugHttpRequest(req, "");
return this.request(req);
}
/**
* Send a DELETE request
* @param cluster the cluster definition
* @param path the path or URI
* @return a Response object with response detail
* @throws IOException for error
*/
public Response delete(Cluster cluster, String path) throws IOException {
HttpDelete method = new HttpDelete(path);
try {
HttpResponse resp = execute(cluster, method, null, path);
Header[] headers = resp.getAllHeaders();
byte[] content = getResponseBody(resp);
return new Response(resp.getStatusLine().getStatusCode(), headers, content);
} finally {
method.releaseConnection();
}
}
static Stream<Arguments> successfulEmptyRequestCreation()
{
return Stream.of(
Arguments.of(HttpMethod.GET, HttpGet.class),
Arguments.of(HttpMethod.HEAD, HttpHead.class),
Arguments.of(HttpMethod.DELETE, HttpDelete.class),
Arguments.of(HttpMethod.OPTIONS, HttpOptions.class),
Arguments.of(HttpMethod.TRACE, HttpTrace.class),
Arguments.of(HttpMethod.POST, HttpPost.class),
Arguments.of(HttpMethod.PUT, HttpPutWithoutBody.class),
Arguments.of(HttpMethod.DEBUG, HttpDebug.class)
);
}
public boolean issueDeleteRequest(URI resourceUri) {
HttpDelete deleteRequest = new HttpDelete(resourceUri);
HttpResponse response = sendRequest(deleteRequest);
int responseStatusCode = response.getStatusLine().getStatusCode();
boolean deletionSuccessful = false;
if(responseStatusCode == 204) {
deletionSuccessful = true;
}
return deletionSuccessful;
}
@Test
public void deleteLabel_sendsDeleteRequest() throws Exception {
// arrange
CloseableHttpClient httpClientMock = recordHttpClientForSingleResponseWithContentAndStatusCode("", 200);
ConfluenceRestClient confluenceRestClient = new ConfluenceRestClient(CONFLUENCE_ROOT_URL, httpClientMock, null, null);
// act
confluenceRestClient.deleteLabel("123456", "foo");
// assert
verify(httpClientMock, times(1)).execute(any(HttpDelete.class));
}
/**
* httpClient delete 删除资源
* @param url
* @return
*/
public static String delete(String url) {
log.info(url);
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpDelete httpDelete = new HttpDelete(url);
CloseableHttpResponse response = httpClient.execute(httpDelete);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error(e);
}
return null;
}
@Test
@Category({
LDP.class,
HappyPath.class
})
@OperateOnDeployment(DEPLOYMENT)
public void testClientContainerSimulation(@ArquillianResource final URL url) throws Exception {
LOGGER.info("Started {}",testName.getMethodName());
HELPER.base(url);
HELPER.setLegacy(false);
HttpGet get = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH,HttpGet.class);
HttpPost post = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH,HttpPost.class);
post.setEntity(
new StringEntity(
TEST_SUITE_BODY,
ContentType.create("text/turtle", "UTF-8"))
);
HELPER.httpRequest(get);
String location = HELPER.httpRequest(post).location;
HELPER.httpRequest(get);
String path=HELPER.relativize(location);
HELPER.httpRequest(HELPER.newRequest(path,HttpOptions.class));
HELPER.httpRequest(HELPER.newRequest(path,HttpGet.class));
HELPER.httpRequest(HELPER.newRequest(path,HttpDelete.class));
HELPER.httpRequest(HELPER.newRequest(path,HttpGet.class));
HELPER.httpRequest(get);
LOGGER.info("Completed {}",testName.getMethodName());
}
@Test
public void testDeleteModel() throws Exception {
Model model = null;
try {
Calendar now = Calendar.getInstance();
now.set(Calendar.MILLISECOND, 0);
processEngineConfiguration.getClock().setCurrentTime(now.getTime());
model = repositoryService.newModel();
model.setCategory("Model category");
model.setKey("Model key");
model.setMetaInfo("Model metainfo");
model.setName("Model name");
model.setVersion(2);
repositoryService.saveModel(model);
HttpDelete httpDelete = new HttpDelete(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId()));
closeResponse(executeRequest(httpDelete, HttpStatus.SC_NO_CONTENT));
// Check if the model is really gone
assertThat(repositoryService.createModelQuery().modelId(model.getId()).singleResult()).isNull();
model = null;
} finally {
if (model != null) {
try {
repositoryService.deleteModel(model.getId());
} catch (Throwable ignore) {
// Ignore, model might not be created
}
}
}
}
@Test
public void deleteAllowed() throws Exception{
HttpUriRequest request = new HttpDelete(defaultURI("/1"));
request.setHeader("Referer","http://somewhere.com");
response = client.execute(request);
assertEquals("status", HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode());
}
public String livyDeleteBatches(String jobId) throws IOException {
String url = baseUrl + "/batches/" + jobId;
HttpDelete delete = new HttpDelete(url);
HttpResponse response = client.execute(delete);
String content = getContent(response);
if (response.getStatusLine().getStatusCode() != 200) {
throw new IOException("Invalid response " + response.getStatusLine().getStatusCode() + " with url " + url + "\n");
}
return content;
}
private static int sendDELETE(String endpoint, String acceptType) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpDelete httpDelete = new HttpDelete(endpoint);
httpDelete.setHeader("Accept", acceptType);
HttpResponse httpResponse = httpClient.execute(httpDelete);
return httpResponse.getStatusLine().getStatusCode();
}
/**
* Test deleting an unexisting deployment. DELETE repository/deployments/{deploymentId}
*/
@Test
public void testDeleteUnexistingDeployment() throws Exception {
HttpDelete httpDelete = new HttpDelete(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_DEPLOYMENT, "unexisting"));
CloseableHttpResponse response = executeRequest(httpDelete, HttpStatus.SC_NOT_FOUND);
closeResponse(response);
}
private void deleteRestServer() throws ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope(host, 8002),
new UsernamePasswordCredentials(username, password));
HttpDelete delete = new HttpDelete(
"http://"
+ host
+ ":8002/v1/rest-apis/java-unittest?include=modules&include=content");
client.execute(delete);
}
public String delete(Object[] params){
HttpDelete httpDelete = null;
try{
} catch(Exception e) {
} finally {
}
return null;
}
/**
* Test deleting a single deployment. DELETE repository/deployments/{deploymentId}
*/
public void testDeleteDeployment() throws Exception {
EventDeployment existingDeployment = repositoryService.createDeployment().name("Deployment 1").category("DEF")
.addClasspathResource("org/flowable/eventregistry/rest/service/api/repository/simpleEvent.event")
.deploy();
// Delete the deployment
HttpDelete httpDelete = new HttpDelete(SERVER_URL_PREFIX + EventRestUrls.createRelativeResourceUrl(EventRestUrls.URL_DEPLOYMENT, existingDeployment.getId()));
CloseableHttpResponse response = executeRequest(httpDelete, HttpStatus.SC_NO_CONTENT);
closeResponse(response);
existingDeployment = repositoryService.createDeploymentQuery().deploymentId(existingDeployment.getId()).singleResult();
assertThat(existingDeployment).isNull();
}
public static String sendHttpDelete(Session session,String url,String user) throws AppJointErrorException {
String resultString = "{}";
HttpDelete httpdelete = new HttpDelete(url);
//设置header
VisualisSession visualisSession = (VisualisSession)session;
String token = visualisSession.getParameters().get("Token-Code");
logger.info("sendDeleteReq url is: "+url+",session:"+token );
httpdelete.addHeader(HTTP.CONTENT_ENCODING, "UTF-8");
httpdelete.addHeader("Token-User",user);
httpdelete.addHeader("Token-Code",token);
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
response = httpClient.execute(httpdelete);
HttpEntity ent = response.getEntity();
resultString = IOUtils.toString(ent.getContent(), "utf-8");
logger.info("Send Http Delete Request Success", resultString);
} catch (Exception e) {
logger.error("Send Http Delete Request Failed", e);
throw new AppJointErrorException(42001, e.getMessage(), e);
}finally{
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(httpClient);
}
return resultString;
}