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


Java CloseableHttpResponse.close方法代碼示例

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


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

示例1: doDownload

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
/**
 * 通過httpClient get 下載文件
 *
 * @param url      網絡文件全路徑
 * @param savePath 保存文件全路徑
 * @return 狀態碼 200表示成功
 */
public static int doDownload(String url, String savePath) {
	// 創建默認的HttpClient實例.
	CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
	HttpGet get = new HttpGet(url);
	CloseableHttpResponse closeableHttpResponse = null;
	try {
		closeableHttpResponse = closeableHttpClient.execute(get);
		HttpEntity entity = closeableHttpResponse.getEntity();
		if (entity != null) {
			InputStream in = entity.getContent();
			FileOutputStream out = new FileOutputStream(savePath);
			IOUtils.copy(in, out);
			EntityUtils.consume(entity);
			closeableHttpResponse.close();
		}
		int code = closeableHttpResponse.getStatusLine().getStatusCode();
		closeableHttpClient.close();
		return code;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		closeSource(closeableHttpClient, closeableHttpResponse);
	}
	return 0;
}
 
開發者ID:CharleyXu,項目名稱:tulingchat,代碼行數:33,代碼來源:HttpClientUtil.java

示例2: sendDeleteCommand

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
/**
 * sendDeleteCommand
 *
 * @param url
 * @return
 */
public Map<String, String> sendDeleteCommand(String url, Map<String, Object> credentials)
        throws ManagerResponseException {
    Map<String, String> response = new HashMap<String, String>();
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpDelete httpDelete = new HttpDelete(url);
    CloseableHttpResponse httpResponse;
    try {
        httpResponse = httpclient.execute(httpDelete, localContext);
        ResponseHandler<String> handler = new CustomResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put("body", body);
        httpResponse.close();
    } catch (Exception e) {
        throw new ManagerResponseException(e.getMessage(), e);
    }

    return response;
}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:26,代碼來源:RestUtils.java

示例3: getResponseString

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
/**
 * 轉換返回內容為string
 * @param responseBody
 * @param response
 * @return
 * @throws IOException
 */
private String getResponseString(String responseBody, CloseableHttpResponse response) throws IOException {
    try {
        logger.info(String.valueOf(response.getStatusLine()));
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            responseBody = EntityUtils.toString(entity);
        } else {
            logger.info("http return status error:" + response.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        response.close();
    }
    return responseBody;
}
 
開發者ID:gongjunhao,項目名稱:car-bjpermit,代碼行數:24,代碼來源:HttpClientUtils.java

示例4: send

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
public ProducedEventResult send(Map<Object, Object> event) throws IOException, PyroclastAPIException {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        String url = String.format("%s/%s/produce", this.endpoint, this.topicId);
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Authorization", this.writeApiKey);
        httpPost.addHeader("Content-type", this.format);

        String jsonString = MAPPER.writeValueAsString(event);
        HttpEntity entity = new ByteArrayEntity(jsonString.getBytes());
        httpPost.setEntity(entity);

        CloseableHttpResponse response;

        response = httpClient.execute(httpPost);
        ResponseParser<ProducedEventResult> parser = new ProduceEventParser();
        ProducedEventResult result = parser.parseResponse(response, MAPPER);
        response.close();

        return result;
    }
}
 
開發者ID:PyroclastIO,項目名稱:pyroclast-java,代碼行數:22,代碼來源:PyroclastProducer.java

示例5: sendGet

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
public static String sendGet(String url) {  
    CloseableHttpResponse response = null;  
    String content = null;  
    try {  
        HttpGet get = new HttpGet(url);  
        response = httpClient.execute(get, context);  
        HttpEntity entity = response.getEntity();  
        content = EntityUtils.toString(entity);  
        EntityUtils.consume(entity);  
        return content;  
    } catch (Exception e) {  
        e.printStackTrace();  
        if (response != null) {  
            try {  
                response.close();  
            } catch (IOException e1) {  
                e1.printStackTrace();  
            }  
        }  
    }  
    return content;  
}
 
開發者ID:bluetata,項目名稱:crawler-jsoup-maven,代碼行數:23,代碼來源:HttpUtil.java

示例6: execute

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的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:CableIM,項目名稱:Cable-Android,代碼行數:26,代碼來源:LegacyMmsConnection.java

示例7: httpPost

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
private String httpPost(String postUrl, Map<String, String> paramMap) throws ClientProtocolException, IOException {
	CloseableHttpResponse response = null;
	try {
		HttpPost post = new HttpPost(postUrl);
		HttpEntity entity = new UrlEncodedFormEntity(getNameValuePairs(paramMap), UTF8);
		post.setEntity(entity);
		response = getHttpClient().execute(post);
		return EntityUtils.toString(response.getEntity(), UTF8);
	} finally {
		if (null != response) {
			response.close();
		}
	}
}
 
開發者ID:JK-River,項目名稱:RobotServer,代碼行數:15,代碼來源:HttpService.java

示例8: doGet

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
/**
 * HTTP Get 獲取內容
 *
 * @param url     請求的url地址 ?之前的地址
 * @param params  請求的參數
 * @param charset 編碼格式
 * @return 頁麵內容
 */
public static String doGet(String url, Map<String, String> params, String charset) throws Exception {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    try {
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String value = entry.getValue();
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
            url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
        }
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpGet.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
        }
        EntityUtils.consume(entity);
        response.close();
        return result;
    } catch (Exception e) {
        throw e;
    }
}
 
開發者ID:fanqinghui,項目名稱:wish-pay,代碼行數:43,代碼來源:HttpClientUtils.java

示例9: login

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
/**
 * Perform a http login and return the acquired session ID.
 *
 * @param credentials the credentials to login with
 * @param csrfToken   the csrfToken form the login page
 *
 * @param forwardedForHeader
 * @return the sessionId if login was successful
 *
 * @throws IOException
 */
private Optional<String> login(Credentials credentials, String csrfToken, Header forwardedForHeader) throws IOException {
    Optional<String> sessionId;
    CloseableHttpClient httpclient = HttpClientBuilder.create()
            .setRedirectStrategy(new LaxRedirectStrategy())
            .build();

    try {
        HttpPost httpPost = new HttpPost(configuration.getLoginUrl());
        httpPost.setHeader(forwardedForHeader);

        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("username", credentials.getUsername()));
        nvps.add(new BasicNameValuePair("password", credentials.getPassword()));
        nvps.add(new BasicNameValuePair("_csrf", csrfToken));

        String initialSession = getCurrentSession(context);

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response2 = httpclient.execute(httpPost, context);

        try {
            logger.debug(response2.getStatusLine().toString());
            sessionId = extractSessionId(context);
            if(initialSession != null && initialSession.equals(sessionId.orElse("nothing"))){
                return Optional.empty();
            }
        } finally {
            response2.close();
        }

    } finally {
        httpclient.close();
    }
    return sessionId;
}
 
開發者ID:iteratec,項目名稱:security-karate,代碼行數:47,代碼來源:LoginExecutor.java

示例10: getResponseInternal0

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
private String getResponseInternal0(String baseUrl, String resourcePath) throws UnsupportedOperationException, IOException {
	CloseableHttpResponse response = null;
	String json = "";
	try {
		HttpUriRequest request = new HttpGet(new URI(baseUrl + "/" + resourcePath));
		response = client.execute(request);
		json = IOUtils.toString(response.getEntity().getContent());
	} catch(Exception e) {
		LOGGER.error("Failed to execute request {} : {}",resourcePath,e);
	} finally {
		if(response != null) response.close();
	}	
	return json;
}
 
開發者ID:cool-mist,項目名稱:DiscordConvenienceBot,代碼行數:15,代碼來源:SteamClient.java

示例11: doPost

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
public String doPost(String url,List <NameValuePair> nvps,BasicCookieStore loginStatus) throws Exception{
	 
       CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(loginStatus).build();
       String webStr = "";
	try {
		//1Post請求
           HttpPost httpPost = new HttpPost(url);
           httpPost.setConfig(requestConfig);//設置超時配置
           
           	/*
           	 * nvps 內容
           	 * List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		     * //網頁post參數 http://www.scnj.tv/appqy_api/api.php?api_key=AaPpQqYyCcOoMmLl&opt=getCategory
		     * nvps.add(new BasicNameValuePair("api_key", WEB_KEY));
		     * nvps.add(new BasicNameValuePair("opt", "login"));
		     * nvps.add(new BasicNameValuePair("uid", uid));
		     * nvps.add(new BasicNameValuePair("pass", password));
           	 * */
           	
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));//需加上UTF8 不然提交出去到網站會變成亂碼 TODO 以後需要提取配置編碼
			 
			CloseableHttpResponse response2;
			//2發送請求
			response2 = httpclient.execute(httpPost);
			System.out.println(response2.getStatusLine());
               //3處理響應結果
               if (response2.getStatusLine().getStatusCode() == 200) {
               	//4從輸入流讀取網頁字符串內容
               	HttpEntity entity2 = response2.getEntity();
                   InputStream in = entity2.getContent();
                   webStr = readResponse(in);
                   //log.debug("網絡請求接收到的返回數據"+webStr);
                   EntityUtils.consume(entity2);
               }
               // and ensure it is fully consumed
               response2.close();
	}catch(java.io.IOException e){
		e.getStackTrace();
		log.error("Web服務器端網絡異常!info:"+e.getStackTrace().toString());
	}
	finally {
	//始終保持執行
          httpclient.close();
          
	}
	return webStr;
 
}
 
開發者ID:Xvms,項目名稱:xvms,代碼行數:49,代碼來源:HttpTookit.java

示例12: download

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
@Override
public String download(String url) throws IOException {
    HttpGet httpGet = new HttpGet(url);
    for(Map.Entry<String,String> header : this.headers().entrySet()){
        httpGet.setHeader(header.getKey(),header.getValue());
    }
    CloseableHttpResponse response = this.httpClient.execute(httpGet);
    String content = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
    response.close();
    return content;
}
 
開發者ID:StevenKin,項目名稱:ZhihuQuestionsSpider,代碼行數:12,代碼來源:AbstractProxySite.java

示例13: doPost

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
/**
 * HTTP Post 獲取內容
 *
 * @param url     請求的url地址 ?之前的地址
 * @param params  請求的參數
 * @param charset 編碼格式
 * @return 頁麵內容
 */
public static String doPost(String url, Map<String, String> params, String charset) throws Exception {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    try {
        List<NameValuePair> pairs = null;
        if (params != null && !params.isEmpty()) {
            pairs = new ArrayList<>(params.size());
            //去掉NameValuePair轉換,這樣就可以傳遞Map<String,Object>
            /*pairs = new ArrayList<NameValuePair>(params.size());*/
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String value = entry.getValue();
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
        }
        HttpPost httpPost = new HttpPost(url);
        if (pairs != null && pairs.size() > 0) {
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
        }
        CloseableHttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
        }
        EntityUtils.consume(entity);
        response.close();
        return result;
    } catch (Exception e) {
        throw e;
    }
}
 
開發者ID:fanqinghui,項目名稱:wish-pay,代碼行數:48,代碼來源:HttpClientUtils.java

示例14: channelMembersIds

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
public Users channelMembersIds(String id) throws IOException, URISyntaxException {
    HttpGet req = new HttpGet(url(String.format(CHANNEL_MEMBERS_IDS_URL, this.teams[0].getTeamId())));
    //		req.setEntity(new StringEntity("['"+this.user.getId()+"']"));
    req.addHeader("Content-Type", "application/json");
    req.addHeader("Authorization", "Bearer " + this.token);
    CloseableHttpResponse resp = this.client.execute(req);
    try {
        String msg = IOUtils.toString(resp.getEntity().getContent(), "UTF-8");
        System.out.println(msg);
        resp.close();
        return gson.fromJson(msg, Users.class);
    } catch (JsonSyntaxException e) {
        return new Users();
    }
}
 
開發者ID:stefandotti,項目名稱:intellij-mattermost-plugin,代碼行數:16,代碼來源:MattermostClient.java

示例15: teams

import org.apache.http.client.methods.CloseableHttpResponse; //導入方法依賴的package包/類
public void teams() throws IOException, URISyntaxException {
    HttpGet req = new HttpGet(url(TEAMS_URL));
    req.addHeader("Content-Type", "application/json");
    req.addHeader("Authorization", "Bearer " + this.token);
    CloseableHttpResponse resp = this.client.execute(req);
    String json = IOUtils.toString(resp.getEntity().getContent(), "UTF-8");
    this.teams = gson.fromJson(json, TeamMember[].class);
    resp.close();
}
 
開發者ID:stefandotti,項目名稱:intellij-mattermost-plugin,代碼行數:10,代碼來源:MattermostClient.java


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