当前位置: 首页>>代码示例>>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;未经允许,请勿转载。