addHeader()源码实例Demo

org.apache.http.client.methods.HttpDelete#addHeader()源码实例Demo

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

源代码1 项目: cxf   文件: CrossOriginSimpleTest.java
@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();
    }
}
 
源代码2 项目: sdk   文件: AviSDKMockTest.java
@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());
	}
}
 
源代码3 项目: zerocode   文件: RestEndPointMockerTest.java
@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));

}
 
源代码4 项目: ZTuoExchange_framework   文件: CaiPiaoHttpUtils.java
/**
 * 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);
   }
 
源代码5 项目: AIDR   文件: Communicator.java
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();

}
 
源代码6 项目: ZTuoExchange_framework   文件: CaiPiaoHttpUtils.java
/**
 * 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);
   }
 
源代码7 项目: charging_pile_cloud   文件: AliHttpUtils.java
/**
 * 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);
}
 
源代码8 项目: DataSphereStudio   文件: HttpUtils.java
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;
}
 
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");
    }
}
 
@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);
}
 
源代码11 项目: api-gateway-demo-sign-java   文件: HttpUtils.java
/**
 * 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);
   }
 
源代码12 项目: api-gateway-demo-sign-java   文件: HttpUtil.java
/**
 * 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));
}
 
源代码13 项目: restfiddle   文件: DeleteHandler.java
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;
   }
 
源代码14 项目: Examples   文件: HttpDeleteExample.java
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();
    }
}
 
源代码15 项目: io   文件: DcRestAdapter.java
/**
 * 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);
}
 
源代码16 项目: java-client-api   文件: ConnectedRESTQA.java
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();
}
 
源代码17 项目: olingo-odata4   文件: TripPinServiceTest.java
@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));
}
 
源代码18 项目: fido2   文件: RestFidoActionsOnPolicy.java
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("******************************************");
}
 
源代码19 项目: fido2   文件: RestFidoActionsOnPolicy.java
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("******************************************");
}
 
源代码20 项目: AIDR   文件: PybossaCommunicator.java
@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();

}
 
源代码评论
动弹
沙发等你来抢