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


Java CloseableHttpResponse類代碼示例

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


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

示例1: sendHttpPut

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
@Override
public <REQ> CloseableHttpResponse sendHttpPut(String url, REQ request) {
    CloseableHttpResponse execute = null;
    String requestJson = GsonUtils.toJson(request);

    try {
        LOGGER.log(Level.FINER, "Send PUT request:" + requestJson + " to url-" + url);
        HttpPut httpPut = new HttpPut(url);
        StringEntity entity = new StringEntity(requestJson, "UTF-8");
        entity.setContentType("application/json");
        httpPut.setEntity(entity);
        execute = this.httpClientFactory.getHttpClient().execute(httpPut);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Was unable to send PUT request:" + requestJson
            + " (displaying first 1000 chars) from url-" + url, e);
    }

    return execute;
}
 
開發者ID:SoftGorilla,項目名稱:restheart-java-client,代碼行數:20,代碼來源:HttpConnectionUtils.java

示例2: checkOrderInfo

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
public static String checkOrderInfo(TrainQuery query) {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.checkOrderInfo);

    httpPost.addHeader(CookieManager.cookieHeader());

    httpPost.setEntity(new StringEntity(genCheckOrderInfoParam(query), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));

    String result = StringUtils.EMPTY;
    try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
        CookieManager.touch(response);
        result = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        logger.error("checkUser error", e);
    }

    return result;
}
 
開發者ID:justice-code,項目名稱:Thrush,代碼行數:19,代碼來源:HttpRequest.java

示例3: getErc20TokenTotalSupply

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
/**
 * Get ERC20-Token total supply by contract address
 * @param contractAddress Contract address
 * @return ERC20-Token total supply
 */
public BigInteger getErc20TokenTotalSupply(String contractAddress) {

	HttpGet get = new HttpGet(PUBLIC_URL + "?module=stats&action=tokensupply&contractaddress=" + contractAddress + "&apikey=" + API_KEY);
	String response = null;

	try(CloseableHttpResponse httpResponse = httpClient.execute(get)) {
		HttpEntity httpEntity = httpResponse.getEntity();
		response = EntityUtils.toString(httpEntity);
		EntityUtils.consume(httpEntity);
	} catch (IOException e) {
		e.printStackTrace();
	}

	@SuppressWarnings("rawtypes")
	ArrayList<CustomNameValuePair<String, CustomNameValuePair>> a = Utility.evaluateExpression(response);

	for(int j = 0; j < a.size(); j++)
		if(a.get(j).getName().toString().equals("result"))
			return new BigInteger(a.get(j).getValue().toString());

	return null;  // Null should not be expected when API is functional

}
 
開發者ID:Jaewan-Yun,項目名稱:Cryptocurrency-Java-Wrappers,代碼行數:29,代碼來源:Etherscan.java

示例4: getJsonFromCAdvisor

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
@Override
public String getJsonFromCAdvisor(String containerId) {
	String result = "";
	try {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.3/containers/docker/" + containerId);
		CloseableHttpResponse response = httpclient.execute(httpget);
		try {
			result = EntityUtils.toString(response.getEntity());
			if (logger.isDebugEnabled()) {
				logger.debug(result);
			}
		} finally {
			response.close();
		}
	} catch (Exception e) {
		logger.error(containerId, e);
	}
	return result;
}
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:21,代碼來源:MonitoringServiceImpl.java

示例5: sendHttpPost

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
@Override
public <REQ> CloseableHttpResponse sendHttpPost(String url, REQ request) {
    CloseableHttpResponse execute = null;
    String requestJson = GsonUtils.toJson(request);

    try {
        LOGGER.log(Level.FINER, "Send POST request:" + requestJson + " to url-" + url);
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(requestJson, "UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        execute = this.httpClientFactory.getHttpClient().execute(httpPost);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "was unable to send POST request:" + requestJson
            + " (displaying first 1000 chars) from url-" + url, e);
    }

    return execute;
}
 
開發者ID:SoftGorilla,項目名稱:restheart-java-client,代碼行數:20,代碼來源:HttpConnectionUtils.java

示例6: post

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
/**
 * httpClient post 獲取資源
 * @param url
 * @param params
 * @return
 */
public static String post(String url, Map<String, Object> params) {
	log.info(url);
	try {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);
		if (params != null && params.size() > 0) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				Object object = params.get(key);
				nvps.add(new BasicNameValuePair(key, object==null?null:object.toString()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
		}
		CloseableHttpResponse response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	} catch (Exception e) {
		log.error(e);
	}
	return null;
}
 
開發者ID:mumucommon,項目名稱:mumu-core,代碼行數:28,代碼來源:HttpClientUtil.java

示例7: doResponse

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
/**
 * 處理返回結果數據
 *
 * @param unitTest
 * @param response
 * @throws IOException
 */
private static void doResponse(UnitTest unitTest, CloseableHttpResponse response) throws IOException {
    int statusCode = response.getStatusLine().getStatusCode();
    unitTest.setResponseCode(statusCode);
    StringBuffer sb = new StringBuffer();
    for (int loop = 0; loop < response.getAllHeaders().length; loop++) {
        BufferedHeader header = (BufferedHeader) response
                .getAllHeaders()[loop];
        if (header.getName().equals("Accept-Charset")) {
            continue;
        }
        sb.append(header.getName() + ":" + header.getValue() + "<br/>");
    }
    unitTest.setResponseHeader(sb.toString());
    HttpEntity entity = response.getEntity();
    String result;
    if (entity != null) {
        result = EntityUtils.toString(entity, "utf-8");
        unitTest.setResponseSize(result.getBytes().length);
        unitTest.setResponseBody(result);
    }
    EntityUtils.consume(entity);
    response.close();
}
 
開發者ID:melonlee,項目名稱:PowerApi,代碼行數:31,代碼來源:HttpUtil.java

示例8: jButtonDetenerActionPerformed

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
private void jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost("http://" + ip + ":8080/proyecto-gson/servidordetener?id=" + user.getId());

            CloseableHttpResponse response = httpclient.execute(httppost);
            System.out.println(response.getStatusLine());

            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
            response.close();
        } catch (IOException ex) {
            Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
        user = null;
        jLabel1.setForeground(Color.red);
        url.setText("");
        jlabelSQL.setText("");
        this.setTitle("App [ID:?]");
    }
 
開發者ID:AmauryOrtega,項目名稱:Sem-Update,代碼行數:22,代碼來源:VentanaPrincipal.java

示例9: checkUser

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
public static String checkUser() {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.checkUser);

    httpPost.addHeader(CookieManager.cookieHeader());

    String result = StringUtils.EMPTY;
    try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
        CookieManager.touch(response);
        result = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        logger.error("checkUser error", e);
    }

    return result;
}
 
開發者ID:justice-code,項目名稱:Thrush,代碼行數:17,代碼來源:HttpRequest.java

示例10: main

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
public static void main(String[] args) throws IOException, URISyntaxException {
	ObjectMapper mapper = new ObjectMapper();
	try (CloseableHttpClient client =
				 HttpClientBuilder.create().useSystemProperties().build()) {
		URI uri = new URIBuilder("http://api.geonames.org/searchJSON")
				.addParameter("q", "kabupaten garut")
				.addParameter("username", "ceefour")
				.build();
		HttpGet getRequest = new HttpGet(uri);
		try (CloseableHttpResponse resp = client.execute(getRequest)) {
			String body = IOUtils.toString(resp.getEntity().getContent(),
					StandardCharsets.UTF_8);
			JsonNode bodyNode = mapper.readTree(body);
			LOG.info("Status: {}", resp.getStatusLine());
			LOG.info("Headers: {}", resp.getAllHeaders());
			LOG.info("Body: {}", body);
			LOG.info("Body (JsonNode): {}", bodyNode);
			for (JsonNode child : bodyNode.get("geonames")) {
				LOG.info("Place: {} ({}, {})", child.get("toponymName"), child.get("lat"), child.get("lng"));
			}
		}
	}
}
 
開發者ID:ceefour,項目名稱:java-web-services-training,代碼行數:24,代碼來源:Jws1042Application.java

示例11: doGet_should_return_string_response_since_httpClient_execute_returned_with_success

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
@Test(groups = "HttpUtils.doGet")
public void doGet_should_return_string_response_since_httpClient_execute_returned_with_success()
        throws ClientProtocolException, IOException {

    String succResponse = "Test Response";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(succResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(200);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);
    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("test", "value");

    try {
        String response = HttpUtils.doGet("http://example.com", headers);

        Assert.assertEquals(response, succResponse);
    } catch (StockException e) {
        Assert.fail("Exception occured while calling HttpUtils.doGet!", e);
    }
}
 
開發者ID:adobe,項目名稱:stock-api-sdk,代碼行數:41,代碼來源:HttpUtilsTest.java

示例12: execute

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
@Override
public StatusResult execute() throws ClientProtocolException, IOException {
	String recipients = "\"" + String.join("\",\"", this.recipients.toArray(new String[0])) + "\"";
	List<Map<String, String>> data = new ArrayList<Map<String, String>>();

	Map<String, String> map = new HashMap<String, String>();
	if (shareType == ShareType.MEDIA) {
		map.put("type", "form-data");
		map.put("name", "media_id");
		map.put("data", mediaId);
		data.add(map);
	}

	map = map.size() > 0 ? new HashMap<String, String>() : map;
	map.put("type", "form-data");
	map.put("name", "recipient_users");
	map.put("data", "[[" + recipients + "]]");
	data.add(map);

	map = new HashMap<String, String>();
	map.put("type", "form-data");
	map.put("name", "client_context");
	map.put("data", InstagramGenericUtil.generateUuid(true));
	data.add(map);

	map = new HashMap<String, String>();
	map.put("type", "form-data");
	map.put("name", "thread_ids");
	map.put("data", "[]");
	data.add(map);

	map = new HashMap<String, String>();
	map.put("type", "form-data");
	map.put("name", "text");
	map.put("data", message == null ? "" : message);
	data.add(map);

	HttpPost post = createHttpRequest();
	post.setEntity(new ByteArrayEntity(buildBody(data, api.getUuid()).getBytes(StandardCharsets.UTF_8)));

	try (CloseableHttpResponse response = api.getClient().execute(post)) {
		api.setLastResponse(response);

		int resultCode = response.getStatusLine().getStatusCode();
		String content = EntityUtils.toString(response.getEntity());

		log.info("Direct-share request result: " + resultCode + ", " + content);

		post.releaseConnection();

		StatusResult result = parseResult(resultCode, content);

		return result;
	}
}
 
開發者ID:brunocvcunha,項目名稱:instagram4j,代碼行數:56,代碼來源:InstagramDirectShareRequest.java

示例13: acknowledgeEvents

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
/**
 * Acknowledges events. Acknowledged events are not returned in subsequent
 * Get Event calls. Subsequent API calls for the events, such as Post
 * Document Update and Resume, will not work until Acknowledge has been
 * called.
 * 
 * @param eventIds
 *            list of events' ids to be acknowledged.
 * @throws UnsuccessfulOperationException
 *             when acknowledge fails.
 */
public void acknowledgeEvents(List<String> eventIds) throws UnsuccessfulOperationException {

	String acknowledgeEventsJson = getAcknowledgeEventsJson(eventIds);

	Map<String, String> headers = new HashMap<String, String>();
	headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
	headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);

	logger.debug(DEBUG_CALLING_URI_WITH_PAYLOAD_MESSAGE, acknowledgeEventsPath, acknowledgeEventsJson);
	try (CloseableHttpResponse acknowledgeEventsResponse = openApiEndpoint.executeHttpPost(acknowledgeEventsPath,
			headers, acknowledgeEventsJson);) {
		int acknowledgeEventsResponseStatusCode = HttpResponseUtils
				.validateHttpStatusResponse(acknowledgeEventsResponse, HttpStatus.SC_OK);

		logger.debug(DEBUG_CALLING_URI_RETURNED_STATUS_MESSAGE, acknowledgeEventsPath,
				acknowledgeEventsResponseStatusCode);
	} catch (IOException | HttpResponseException e) {
		String errorMessage = MessageFormat.format(ERROR_PROBLEM_OCCURED_WHILE_CALLING_URI_MESSAGE,
				acknowledgeEventsPath);
		logger.error(errorMessage);
		throw new UnsuccessfulOperationException(errorMessage, e);
	}

	logger.debug(DEBUG_CALLED_URI_SUCCESSFULLY_MESSAGE, acknowledgeEventsPath);
}
 
開發者ID:SAP,項目名稱:cloud-ariba-partner-flow-extension-ext,代碼行數:37,代碼來源:PartnerFlowExtensionApiFacade.java

示例14: download

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
@Override
public Maybe<Response> download(final Request request) {

    return Maybe.create(new MaybeOnSubscribe<CloseableHttpResponse>(){

        @Override
        public void subscribe(MaybeEmitter emitter) throws Exception {

            emitter.onSuccess(httpManager.getResponse(request));
        }
    }).map(new Function<CloseableHttpResponse, Response>() {

        @Override
        public Response apply(CloseableHttpResponse closeableHttpResponse) throws Exception {

            String html = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
            Response response = new Response();
            response.setContent(html);
            response.setStatusCode(closeableHttpResponse.getStatusLine().getStatusCode());
            return response;
        }
    });
}
 
開發者ID:fengzhizi715,項目名稱:NetDiscovery,代碼行數:24,代碼來源:HttpClientDownloader.java

示例15: gasPrice

import org.apache.http.client.methods.CloseableHttpResponse; //導入依賴的package包/類
/**
 * Returns the current price per gas in Wei
 * @return Current gas price in Wei
 */
public BigInteger gasPrice() {

	HttpGet get = new HttpGet(PUBLIC_URL + "?module=proxy&action=eth_gasPrice" + "&apikey=" + API_KEY);
	String response = null;

	try(CloseableHttpResponse httpResponse = httpClient.execute(get)) {
		HttpEntity httpEntity = httpResponse.getEntity();
		response = EntityUtils.toString(httpEntity);
		EntityUtils.consume(httpEntity);
	} catch (IOException e) {
		e.printStackTrace();
	}

	@SuppressWarnings("rawtypes")
	ArrayList<CustomNameValuePair<String, CustomNameValuePair>> a = Utility.evaluateExpression(response);

	for(int j = 0; j < a.size(); j++)
		if(a.get(j).getName().toString().equals("result"))
			return new BigInteger(a.get(j).getValue().toString().substring(2), 16); // Hex to dec

	return null;  // Null should not be expected when API is functional

}
 
開發者ID:Jaewan-Yun,項目名稱:Cryptocurrency-Java-Wrappers,代碼行數:28,代碼來源:Etherscan.java


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