當前位置: 首頁>>代碼示例>>Java>>正文


Java CloseableHttpClient.close方法代碼示例

本文整理匯總了Java中org.apache.http.impl.client.CloseableHttpClient.close方法的典型用法代碼示例。如果您正苦於以下問題:Java CloseableHttpClient.close方法的具體用法?Java CloseableHttpClient.close怎麽用?Java CloseableHttpClient.close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.http.impl.client.CloseableHttpClient的用法示例。


在下文中一共展示了CloseableHttpClient.close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getCsrfToken

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
/**
 * get the csrf token from the login page's http form
 *
 * @return the csrf token
 *
 * @throws IOException
 * @param forwardedForHeader
 */
private String getCsrfToken(Header forwardedForHeader) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpGet = new HttpGet(configuration.getLoginUrl());
        httpGet.setHeader(forwardedForHeader);
        CloseableHttpResponse response1 = httpclient.execute(httpGet, context);
        try {
            logger.debug(response1.getStatusLine().toString());
            Optional<String> csrfTokenOpt = extractCsrfTokenAndCloseConnection(response1);
            return csrfTokenOpt.orElseThrow(
                    () -> new IllegalStateException("failed to extract csrf token."));
        } finally {
            response1.close();
        }
    } finally {
        httpclient.close();
    }
}
 
開發者ID:iteratec,項目名稱:security-karate,代碼行數:27,代碼來源:LoginExecutor.java

示例2: query

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
private <REQ, RESP> RESP query(REQ request, Class<RESP> clazz) throws IOException, DruidException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(configuration.getUrl());

    StringEntity entity = new StringEntity(mapper.writeValueAsString(request), configuration.getCharset());
    httpPost.setEntity(entity);
    httpPost.setHeader("Content-type", "application/json");

    CloseableHttpResponse response = client.execute(httpPost);
    String content = EntityUtils.toString(response.getEntity(), configuration.getCharset());

    try {
        return mapper.readValue(content, clazz);
    } catch (Exception ex) {
        throw new DruidException(content);
    } finally {
        client.close();
    }
}
 
開發者ID:levin81,項目名稱:daelic,代碼行數:20,代碼來源:DruidClient.java

示例3: execute

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
protected byte[] execute(HttpUriRequest request) throws IOException {
  Log.w(TAG, "connecting to " + apn.getMmsc());

  CloseableHttpClient   client   = null;
  CloseableHttpResponse response = null;
  try {
    client   = constructHttpClient();
    response = client.execute(request);

    Log.w(TAG, "* response code: " + response.getStatusLine());

    if (response.getStatusLine().getStatusCode() == 200) {
      return parseResponse(response.getEntity().getContent());
    }
  } catch (NullPointerException npe) {
    // TODO determine root cause
    // see: https://github.com/WhisperSystems/Signal-Android/issues/4379
    throw new IOException(npe);
  } finally {
    if (response != null) response.close();
    if (client != null)   client.close();
  }

  throw new IOException("unhandled response code");
}
 
開發者ID:XecureIT,項目名稱:PeSanKita-android,代碼行數:26,代碼來源:LegacyMmsConnection.java

示例4: post

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
private String post(String url, List<NameValuePair> nvps) throws IOException{
	CloseableHttpClient httpclient = connectionPoolManage.getHttpClient();
	
	HttpPost httpPost = new HttpPost(url);
	
	if(nvps != null)
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
	
	CloseableHttpResponse response = httpclient.execute(httpPost);
	
	String result = null;
	if(response.getStatusLine().getStatusCode() == 200){
		HttpEntity entity = response.getEntity();
		result = EntityUtils.toString(entity);
	}
	
	httpclient.close();
	
	return result;
}
 
開發者ID:flychao88,項目名稱:dubbocloud,代碼行數:21,代碼來源:MockTestFilter.java

示例5: put

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
private Map put(String url, String data) throws IOException, HttpException {
	Map<String,Object> map = null;
	CredentialsProvider credentials = credentialsProvider();
	CloseableHttpClient httpclient = HttpClients.custom()
               .setDefaultCredentialsProvider(credentials)
               .build();

	try {
		HttpPut httpPut = new HttpPut(url);
 		httpPut.setHeader("Accept", "application/json");
 		httpPut.setHeader("Content-Type", "application/json");
        HttpEntity entity = new ByteArrayEntity(data.getBytes("utf-8"));
 		httpPut.setEntity(entity);
	        
	    System.out.println("Executing request " + httpPut.getRequestLine());
	    CloseableHttpResponse response = httpclient.execute(httpPut);
	    try {
	        LOG.debug("----------------------------------------");
	        LOG.debug((String)response.getStatusLine().getReasonPhrase());
	        String responseBody = EntityUtils.toString(response.getEntity());
	        LOG.debug(responseBody);
	        Gson gson = new Gson();
	        map = new HashMap<String,Object>();
			map = (Map<String,Object>) gson.fromJson(responseBody, map.getClass());
	        LOG.debug(responseBody);
	    } finally {
	        response.close();
	    }
	} finally {
	    httpclient.close();
	}

	return map;
}
 
開發者ID:dellemc-symphony,項目名稱:ticketing-service-paqx-parent-sample,代碼行數:35,代碼來源:TicketingIntegrationService.java

示例6: doGetJson

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
public static JSONObject doGetJson(String url) throws IOException {
    JSONObject jsonObject = null;
    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);

    CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);

    HttpEntity httpEntity = closeableHttpResponse.getEntity();
    if (httpEntity != null) {
        String result = EntityUtils.toString(httpEntity, "UTF-8");
        jsonObject = JSONObject.fromObject(result);
    }
    httpGet.releaseConnection();
    closeableHttpClient.close();
    return jsonObject;
}
 
開發者ID:zxbangban,項目名稱:zxbangban,代碼行數:17,代碼來源:WXAutoUtil.java

示例7: getMessage

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
public String getMessage(String url) {
	String responseString = "";
	
	try {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(URL + url);
	 
	    CloseableHttpResponse response = client.execute(httpGet);
	    
	    if (response.getStatusLine().getStatusCode() != 200) {
	    	responseString = null;;
	    } else {
	    	responseString = EntityUtils.toString(response.getEntity());
	    }
	    
	    client.close();
	} catch (Exception e) {
		e.printStackTrace();
		System.exit(-1);
	}
    
	return responseString;
}
 
開發者ID:gamefest2017,項目名稱:ants,代碼行數:24,代碼來源:Client.java

示例8: post

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
public static String post(final String url, String body, Map<String, String> headers) {
   CloseableHttpClient httpClient = buildClient();
   String json = "";
   try {
      HttpPost request = new HttpPost(url);
      StringEntity params = new StringEntity(body);
      for(Map.Entry<String, String> entry : headers.entrySet()) {
         request.addHeader(entry.getKey(), entry.getValue());
      }
      request.setEntity(params);
      CloseableHttpResponse result = httpClient.execute(request);
      if (result.getEntity() != null) {
         json = EntityUtils.toString(result.getEntity(), DATA_ENCODING);
      }
      result.close();
      httpClient.close();
   }
   catch (IOException ex) {
      json = ex.getMessage();
   }

   return json;
}
 
開發者ID:chen0040,項目名稱:java-magento-client,代碼行數:24,代碼來源:HttpClient.java

示例9: call

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
@Override
public DataTransferObject call() throws Exception {
    CloseableHttpClient httpClient = null;
    DataTransferObject dto = new DataTransferObject();
    CloseableHttpResponse response = null;
    LogInfoBean logInfoBean = new LogInfoBean();
    try {
        /**
         * HTTP connections are complex, stateful, thread-unsafe objects which need to be properly managed to function correctly.
         * HTTP connections can only be used by one execution thread at a time
         */
        httpClient = HttpClients.createDefault();
        logInfoBean.setSmsMessage(smsMessage);
        logInfoBean.setUrl(config.getSendUrl());
        //根據請求設置URL
        response = httpClient.execute(httpPost);
        String result = handlerRespone(response, logInfoBean);
        logger.saveLog(logInfoBean);
        dto.putValue("data", result);
        return dto;
    } catch (IOException e) {
        dto.setErrCode(1);
        dto.setMsg("發送短信失敗:" + e.getMessage());
        LogUtil.error(LOGGER, "send error:{}", e);
        logInfoBean.setReturnInfo(e.getMessage());
        logger.saveLog(logInfoBean);
        return dto;
    } finally {
        if (!Check.NuNObj(httpClient)) {
            httpClient.close();
        }
        if (!Check.NuNObj(response)) {
            response.close();
        }
    }
}
 
開發者ID:AsuraTeam,項目名稱:asura,代碼行數:37,代碼來源:SmsSendWorker.java

示例10: main

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
public static void main(String [] args) throws Exception{
    CloseableHttpClient client = HttpClients.createDefault();
    try{
        HttpGet request = new HttpGet("http://httpbin.org/get");

        CloseableHttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println("Status code: " + statusCode);
        System.out.println("Response Body: " + responseBody);
    }finally{
        client.close();
    }
}
 
開發者ID:PacktPublishing,項目名稱:Java-9-Cookbook,代碼行數:15,代碼來源:ApacheHttpClientDemo.java

示例11: close

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
@Override
public void close(){
    CloseableHttpClient cli = httpClient;
    if (cli != null) {
        httpClient = null;
        try {
            cli.close();
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}
 
開發者ID:bubicn,項目名稱:bubichain-sdk-java,代碼行數:13,代碼來源:HttpServiceConnection.java

示例12: getHtml

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
/**
 * 對上一個方法的重載,使用本機ip進行網站爬取
 */

public static String getHtml(String url) throws ClassNotFoundException,
        IOException {
    String entity = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //設置超時處理
    RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).
            setSocketTimeout(5000).build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(config);

    httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;" +
            "q=0.9,image/webp,*/*;q=0.8");
    httpGet.setHeader("Accept-Encoding", "gzip, deflate, sdch");
    httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
    httpGet.setHeader("Cache-Control", "no-cache");
    httpGet.setHeader("Connection", "keep-alive");
    httpGet.setHeader("Cookie", "_free_proxy_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFVEkiJTRkYjMyM" +
            "TU3NGRjMWVhM2JlMDA5Y2IyNzZlZmVlZTYwBjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMUhtT0pjcnRT" +
            "bm9CZEllSXNTYkNZZWk2Nnp3NGNDcFFSQVFodzk1dmpLZWM9BjsARg%3D%3D--09d8736fbfb9a8544" +
            "b46eef48bb320c2b40ee721; Hm_lvt_0cf76c77469e965d2957f0553e6ecf59=1492128157,149" +
            "2160558,1492347839,1492764281; Hm_lpvt_0cf76c77469e965d2957f0553e6ecf59=1492764295");
    httpGet.setHeader("Host", "www.xicidaili.com");
    httpGet.setHeader("Pragma", "no-cache");
    httpGet.setHeader("Upgrade-Insecure-Requests", "1");
    httpGet.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " +
            "(KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");

    try {
        //客戶端執行httpGet方法,返回響應
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        //得到服務響應狀態碼
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entity = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
        }

        httpResponse.close();
        httpClient.close();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    }

    return entity;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:50,代碼來源:MusicUtils.java

示例13: getHtml1

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
/**
 * 對上一個方法的重載,使用本機ip進行網站爬取
 */

public static String getHtml1(String url) throws ClassNotFoundException,
        IOException {
    String entity = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //設置超時處理
    RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).
            setSocketTimeout(5000).build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(config);

    httpGet.setHeader("Accept", "*/*");
    httpGet.setHeader("Accept-Encoding", "gzip, deflate, sdch");
    httpGet.setHeader("Content-Type", " text/plain;charset=utf-8");
    httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8");

    httpGet.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " +
            "(KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");

    try {
        //客戶端執行httpGet方法,返回響應
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        //得到服務響應狀態碼
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entity = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
        }

        httpResponse.close();
        httpClient.close();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    }

    return entity;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:41,代碼來源:MusicUtils.java

示例14: receive

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
@Override
public DataTransferObject receive() throws IOException {
    CloseableHttpClient httpClient = null;
    DataTransferObject dto = new DataTransferObject();
    CloseableHttpResponse response = null;
    LogInfoBean logInfoBean = new LogInfoBean();
    try {
        /**
         * HTTP connections are complex, stateful, thread-unsafe objects which need to be properly managed to function correctly.
         * HTTP connections can only be used by one execution thread at a time
         */
        httpClient = HttpClients.createDefault();
        logInfoBean.setUrl(config.getSendUrl());
        //根據請求設置URL
        HttpPost httpPost = buildPostParam();
        response = httpClient.execute(httpPost);
        String result = HttpUtil.handlerRespone(response, logInfoBean);
        logger.saveLog(logInfoBean);
        //解析JSON串
        dto = parseReceive(result);
        return dto;
    } catch (Exception e) {
        dto.setErrCode(1);
        dto.setMsg("發送短信失敗:" + e.getMessage());
        LogUtil.error(LOGGER, "send error:{}", e);
        logInfoBean.setReturnInfo(e.getMessage());
        logger.saveLog(logInfoBean);
        return dto;
    } finally {
        if (!Check.NuNObj(httpClient)) {
            httpClient.close();
        }
        if (!Check.NuNObj(response)) {
            response.close();
        }
    }
}
 
開發者ID:AsuraTeam,項目名稱:asura,代碼行數:38,代碼來源:AbstractHttpSmsReceiver.java

示例15: dispatchEventToSalesForce

import org.apache.http.impl.client.CloseableHttpClient; //導入方法依賴的package包/類
private void dispatchEventToSalesForce(String event)
		throws ClientProtocolException, IOException, AuthenticationException {
	CloseableHttpClient client = HttpClients.createDefault();
	HttpPost httpPost = new HttpPost(env.getProperty("sfdc.url"));
	httpPost.setEntity(new StringEntity(event));
	UsernamePasswordCredentials creds = new UsernamePasswordCredentials(env.getProperty("sfdc.username"),
			env.getProperty("sfdc.password"));
	httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));

	CloseableHttpResponse response = client.execute(httpPost);
	log.info("Response from SFDC is {}", response.getStatusLine().getStatusCode());
	client.close();
}
 
開發者ID:ShiftLeftSecurity,項目名稱:HelloShiftLeft,代碼行數:14,代碼來源:CustomerController.java


注:本文中的org.apache.http.impl.client.CloseableHttpClient.close方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。