本文整理汇总了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;
}
示例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;
}
示例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
}
示例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;
}
示例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;
}
示例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;
}
示例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();
}
示例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:?]");
}
示例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;
}
示例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"));
}
}
}
}
示例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);
}
}
示例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;
}
}
示例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;
}
});
}
示例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
}