Java Code Examples for org.apache.http.client.methods.HttpDelete#addHeader()

The following examples show how to use org.apache.http.client.methods.HttpDelete#addHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestEndPointMockerTest.java    From zerocode with Apache License 2.0 6 votes vote down vote up
@Test
public void willMockADELETERequest() throws Exception {

    final MockStep mockDelete = mockSteps.getMocks().get(3);

    stubFor(delete(urlEqualTo(mockDelete.getUrl()))
            .willReturn(aResponse()
                    .withStatus(mockDelete.getResponse().get("status").asInt())
                    .withHeader("Content-Type", APPLICATION_JSON)));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpDelete request = new HttpDelete("http://localhost:9073" + mockDelete.getUrl());
    request.addHeader("Content-Type", "application/json");
    HttpResponse response = httpClient.execute(request);

    assertThat(response.getStatusLine().getStatusCode(), is(204));

}
 
Example 2
Source File: AviSDKMockTest.java    From sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteCall()
		throws ClientProtocolException, IOException, NoSuchMethodException, SecurityException, AviApiException {
	stubFor(delete(urlPathMatching("/api/pool/([a-z0-9-]*)")).willReturn(ok().withStatus(204)));

	CloseableHttpClient httpClient = HttpClients.createDefault();
	HttpDelete request = new HttpDelete("http://localhost:8090/api/pool/pool-0a70a98c-0b7b-4f32-9c93-13a74fcf8201");
	request.addHeader("Content-Type", "application/json");
	HttpResponse httpResponse = httpClient.execute(request);
	verify(deleteRequestedFor(urlPathMatching("/api/pool/pool-0a70a98c-0b7b-4f32-9c93-13a74fcf8201")));
	int responseCode = httpResponse.getStatusLine().getStatusCode();
	if (responseCode > 299) {
		StringBuffer errMessage = new StringBuffer();
		errMessage.append("Failed : HTTP error code : ");
		errMessage.append(responseCode);
		if (null != httpResponse.getEntity()) {
			errMessage.append(" Error Message :");
			errMessage.append(EntityUtils.toString(httpResponse.getEntity()));
		}
		throw new AviApiException(errMessage.toString());
	}
}
 
Example 3
Source File: CrossOriginSimpleTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonSimpleActualRequest() throws Exception {
    configureAllowOrigins(true, null);
    String r = configClient.replacePath("/setAllowCredentials/false")
        .accept("text/plain").post(null, String.class);
    assertEquals("ok", r);

    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpDelete httpdelete = new HttpDelete("http://localhost:" + PORT + "/untest/delete");
    httpdelete.addHeader("Origin", "http://localhost:" + PORT);

    HttpResponse response = httpclient.execute(httpdelete);
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertAllowCredentials(response, false);
    assertOriginResponse(true, null, true, response);
    if (httpclient instanceof Closeable) {
        ((Closeable)httpclient).close();
    }
}
 
Example 4
Source File: GraphCommonsHttpRequestExecutor.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Response doDelete(final URL url, final Set<RequestHeader> headers) throws IOException {
    final HttpDelete request = new HttpDelete(url.toString());
    for(RequestHeader header : headers) {
        if(header.getKey().equals(HTTP.TRANSFER_ENCODING)) {
            continue;
        }
        if(header.getKey().equals(HTTP.CONTENT_LEN)) {
            continue;
        }
        request.addHeader(new BasicHeader(header.getKey(), header.getValue()));
    }
    final CloseableHttpResponse response = client.execute(request);
    return new CommonsHttpResponse(response);
}
 
Example 5
Source File: TripPinServiceTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddDelete2ReferenceCollection() throws Exception {
  // add
  String msg = "{\n" +
      "\"@odata.id\": \"/People('russellwhyte')\"\n" +
      "}";
  String editUrl = baseURL + "/People('vincentcalabrese')/Friends/$ref";
  HttpPost postRequest = new HttpPost(editUrl);
  postRequest.setEntity(new StringEntity(msg, ContentType.APPLICATION_JSON));
  postRequest.addHeader("Content-Type", "application/json;odata.metadata=minimal");
  HttpResponse response = httpSend(postRequest, 204);
  EntityUtils.consumeQuietly(response.getEntity());
  
  // get
  response = httpGET(editUrl, 200);
  JsonNode node = getJSONNode(response);
  assertEquals("/People('russellwhyte')",
      ((ArrayNode) node.get("value")).get(2).get("@odata.id").asText());

  //delete
  HttpDelete deleteRequest = new HttpDelete(editUrl+"?$id="+baseURL+"/People('russellwhyte')");
  deleteRequest.addHeader("Content-Type", "application/json;odata.metadata=minimal");
  response = httpSend(deleteRequest, 204);
  EntityUtils.consumeQuietly(response.getEntity());

  // get
  response = httpGET(editUrl, 200);
  node = getJSONNode(response);
  assertNull("/People('russellwhyte')", ((ArrayNode) node.get("value")).get(2));
}
 
Example 6
Source File: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
public static void deleteElementRangeIndexTemporalAxis(String dbName, String axisName) throws Exception {
	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));

	HttpDelete del = new HttpDelete("http://" + host_name + ":" + admin_port + "/manage/v2/databases/" + dbName
			+ "/temporal/axes/" + axisName + "?format=json");

	del.addHeader("Content-type", "application/json");
	del.addHeader("accept", "application/json");

	HttpResponse response = client.execute(del);
	HttpEntity respEntity = response.getEntity();
	if (response.getStatusLine().getStatusCode() == 400) {
		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity, "UTF-8");
		System.out.println(responseString);
	} else if (respEntity != null) {
		// EntityUtils to get the response content
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);
	} else {
		System.out.println("Axis: " + axisName + " deleted");
		System.out.println("==============================================================");
	}
	client.getConnectionManager().shutdown();
}
 
Example 7
Source File: DcRestAdapter.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 8
Source File: HttpDeleteExample.java    From Examples with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare delete request */
    HttpDelete httpDelete = new HttpDelete("http://www.example.com/api/customer");
    /* Add headers to get request */
    httpDelete.addHeader("Authorization", "value");

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            /* Get status code */
            int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Response code: " + httpResponseCode);
            if (httpResponseCode >= 200 && httpResponseCode < 300) {
                /* Convert response to String */
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                return null;
                /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpDelete, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example 9
Source File: DeleteHandler.java    From restfiddle with Apache License 2.0 5 votes vote down vote up
public RfResponseDTO process(RfRequestDTO rfRequestDTO) throws IOException {
RfResponseDTO response = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(rfRequestDTO.getEvaluatedApiUrl());
httpDelete.addHeader("Content-Type", "application/json");
try {
    response = processHttpRequest(httpDelete, httpclient);
} finally {
    httpclient.close();
}
return response;
   }
 
Example 10
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 5 votes vote down vote up
/**
 * HTTP DELETE
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpDelete(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
    headers = initialBasicHeader(HttpMethod.DELETE, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

    HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpDelete delete = new HttpDelete(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        delete.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    return convert(httpClient.execute(delete));
}
 
Example 11
Source File: HttpUtils.java    From api-gateway-demo-sign-java with Apache License 2.0 5 votes vote down vote up
/**
 * Delete
 *  
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @return
 * @throws Exception
 */
public static HttpResponse doDelete(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }
       
       return httpClient.execute(request);
   }
 
Example 12
Source File: GitlabServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private void deleteCommitDiscussionNote(String commitDiscussionNoteURL, Map<String, String> headers) throws IOException {
    //https://docs.gitlab.com/ee/api/discussions.html#delete-a-commit-thread-note
    HttpDelete httpDelete = new HttpDelete(commitDiscussionNoteURL);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpDelete.addHeader(entry.getKey(), entry.getValue());
    }

    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        LOGGER.info("Deleting {} with headers {}", commitDiscussionNoteURL, headers);

        HttpResponse httpResponse = httpClient.execute(httpDelete);
        validateGitlabResponse(httpResponse, 204, "Commit discussions note deleted");
    }
}
 
Example 13
Source File: HttpUtils.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: AliHttpUtils.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
/**
 * Delete
 *
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @return
 * @throws Exception
 */
public static HttpResponse doDelete(String host, String path, String method,
                                    Map<String, String> headers,
                                    Map<String, String> querys)
        throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    return httpClient.execute(request);
}
 
Example 15
Source File: CaiPiaoHttpUtils.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * Delete
 *  
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @return
 * @throws Exception
 */
public static HttpResponse doDelete(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }
       
       return httpClient.execute(request);
   }
 
Example 16
Source File: Communicator.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
public String deleteGet(String url){
    int responseCode = -1;
    HttpClient httpClient = new DefaultHttpClient();
    StringBuffer responseOutput = new StringBuffer();
    try {
        HttpDelete request = new HttpDelete(url);
        request.addHeader("content-type", "application/json");
        HttpResponse response = httpClient.execute(request);
        responseCode = response.getStatusLine().getStatusCode();

        if ( responseCode == 200 || responseCode == 204) {
            if(response.getEntity()!=null){
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));

                String output;
                while ((output = br.readLine()) != null) {
                    responseOutput.append(output);
                }
            }
        }
        else{
            logger.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        	throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }


    }catch (Exception ex) {
    	logger.error("Exception in deleteGet2: " + url,ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    if(responseCode == -1){
        return "Exception";
    }
    return responseOutput.toString();

}
 
Example 17
Source File: CaiPiaoHttpUtils.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * Delete
 *  
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @return
 * @throws Exception
 */
public static HttpResponse doDelete(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }
       
       return httpClient.execute(request);
   }
 
Example 18
Source File: PybossaCommunicator.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public String deleteGet(String url){
    int responseCode = -1;
    HttpClient httpClient = new DefaultHttpClient();
    StringBuffer responseOutput = new StringBuffer();
    try {
        HttpDelete request = new HttpDelete(url);
        request.addHeader("content-type", "application/json");
        HttpResponse response = httpClient.execute(request);
        responseCode = response.getStatusLine().getStatusCode();

        if ( responseCode == 200 || responseCode == 204) {
            if(response.getEntity()!=null){
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));

                String output;
                while ((output = br.readLine()) != null) {
                    responseOutput.append(output);
                }
            }
        }
        else{
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }


    }catch (Exception ex) {
        logger.error("ex Code deleteGet1: " + ex);
        logger.error("ex Code deleteGet2: " + url);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    if(responseCode == -1){
        return "Exception";
    }
    return responseOutput.toString();

}
 
Example 19
Source File: RestFidoActionsOnPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void delete(String REST_URI,
                            String did,
                            String accesskey,
                            String secretkey,
                            String sidpid) throws IOException
{
    System.out.println("Delete policy test");
    System.out.println("******************************************");

    String apiversion = "2.0";

    //  Make API rest call and get response from the server
    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.DELETE_POLICY_ENDPOINT + "/" + sidpid;
    System.out.println("\nCalling delete policy @ " + resourceLoc);

    String contentSHA = "";
    String contentType = "";
    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpDelete httpDelete = new HttpDelete(resourceLoc);
    String requestToHmac = httpDelete.getMethod() + "\n"
            + contentSHA + "\n"
            + contentType + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpDelete.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpDelete.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpDelete.addHeader("Date", currentDate);
    httpDelete.addHeader("strongkey-api-version", apiversion);
    CloseableHttpResponse response = httpclient.execute(httpDelete);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                break;
            case 401:
                System.out.println("Error during delete policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during delete policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during delete policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }

    } finally {
        response.close();
    }

    System.out.println(" Response : " + result);

    System.out.println("\nDelete policy test complete.");
    System.out.println("******************************************");
}
 
Example 20
Source File: RestFidoActionsOnPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void delete(String REST_URI,
                            String did,
                            String accesskey,
                            String secretkey,
                            String sidpid) throws IOException
{
    System.out.println("Delete policy test");
    System.out.println("******************************************");

    String apiversion = "2.0";

    //  Make API rest call and get response from the server
    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.DELETE_POLICY_ENDPOINT + "/" + sidpid;
    System.out.println("\nCalling delete policy @ " + resourceLoc);

    String contentSHA = "";
    String contentType = "";
    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpDelete httpDelete = new HttpDelete(resourceLoc);
    String requestToHmac = httpDelete.getMethod() + "\n"
            + contentSHA + "\n"
            + contentType + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpDelete.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpDelete.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpDelete.addHeader("Date", currentDate);
    httpDelete.addHeader("strongkey-api-version", apiversion);
    CloseableHttpResponse response = httpclient.execute(httpDelete);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                break;
            case 401:
                System.out.println("Error during delete policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during delete policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during delete policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }

    } finally {
        response.close();
    }

    System.out.println(" Response : " + result);

    System.out.println("\nDelete policy test complete.");
    System.out.println("******************************************");
}