本文整理汇总了Java中org.apache.http.impl.client.CloseableHttpClient.execute方法的典型用法代码示例。如果您正苦于以下问题:Java CloseableHttpClient.execute方法的具体用法?Java CloseableHttpClient.execute怎么用?Java CloseableHttpClient.execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.impl.client.CloseableHttpClient
的用法示例。
在下文中一共展示了CloseableHttpClient.execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: client
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
@Test
public void client() throws URISyntaxException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
HttpGet httpget = new HttpGet(uri);
CloseableHttpResponse response = httpclient.execute(httpget);
}
示例2: simplePost
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
/**
* Simple Http Post.
*
* @param path the path
* @param payload the payload
* @return the closeable http response
* @throws URISyntaxException the URI syntax exception
* @throws IOException Signals that an I/O exception has occurred.
* @throws MininetException the MininetException
*/
public CloseableHttpResponse simplePost(String path, String payload)
throws URISyntaxException, IOException, MininetException {
URI uri = new URIBuilder()
.setScheme("http")
.setHost(mininetServerIP.toString())
.setPort(mininetServerPort.getPort())
.setPath(path)
.build();
CloseableHttpClient client = HttpClientBuilder.create().build();
RequestConfig config = RequestConfig
.custom()
.setConnectTimeout(CONNECTION_TIMEOUT_MS)
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
.setSocketTimeout(CONNECTION_TIMEOUT_MS)
.build();
HttpPost request = new HttpPost(uri);
request.setConfig(config);
request.addHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(payload));
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() >= 300) {
throw new MininetException(String.format("failure - received a %d for %s.",
response.getStatusLine().getStatusCode(), request.getURI().toString()));
}
return response;
}
示例3: register
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
private void register(RegisterModel model) throws Exception {
String url = "http://" + properties.getScouter().getHost() + ":" + properties.getScouter().getPort() + "/register";
String param = new Gson().toJson(model);
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type","application/json");
post.setEntity(new StringEntity(param));
CloseableHttpClient client = HttpClientBuilder.create().build();
// send the post request
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
logger.info("Register message sent to [{}] for [{}].", url, model.getObject().getDisplay());
} else {
logger.warn("Register message sent failed. Verify below information.");
logger.warn("[URL] : " + url);
logger.warn("[Message] : " + param);
logger.warn("[Reason] : " + EntityUtils.toString(response.getEntity(), "UTF-8"));
}
}
示例4: postMessage
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
public boolean postMessage(String url, String message) {
boolean ret = true;
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(URL + url);
StringEntity se = new StringEntity(message);
httpPost.setEntity(se);
CloseableHttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
ret = false;
}
client.close();
} catch (Exception e) {
e.printStackTrace();
ret = false;
System.exit(-1);
}
return ret;
}
示例5: delete
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
private void delete(String url) throws IOException, HttpException {
CredentialsProvider credentials = credentialsProvider();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credentials)
.build();
try {
HttpDelete httpDelete = new HttpDelete(url);
httpDelete.setHeader("Accept", "application/json");
System.out.println("Executing request " + httpDelete.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpDelete);
try {
LOG.debug("----------------------------------------");
LOG.debug((String)response.getStatusLine().getReasonPhrase());
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
开发者ID:dellemc-symphony,项目名称:ticketing-service-paqx-parent-sample,代码行数:23,代码来源:TicketingIntegrationService.java
示例6: getJsonFromCAdvisor
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的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;
}
示例7: execute
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
@Override
public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri,
WxMpQrCodeTicket ticket) throws WxErrorException, IOException {
if (ticket != null) {
if (uri.indexOf('?') == -1) {
uri += '?';
}
uri += uri.endsWith("?")
? "ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8")
: "&ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8");
}
HttpGet httpGet = new HttpGet(uri);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpGet.setConfig(config);
}
try (CloseableHttpResponse response = httpclient.execute(httpGet);
InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);) {
Header[] contentTypeHeader = response.getHeaders("Content-Type");
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
// 出错
if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
throw new WxErrorException(WxError.fromJson(responseContent));
}
}
return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg");
} finally {
httpGet.releaseConnection();
}
}
示例8: testUnknownHostException
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
@Test
public void testUnknownHostException() throws IOException {
CloseableHttpClient client = clientBuilder.build();
try {
client.execute(new HttpGet("http://notexisting.example.com"));
} catch (UnknownHostException ex) {
}
List<MockSpan> mockSpans = mockTracer.finishedSpans();
Assert.assertEquals(2, mockSpans.size());
MockSpan mockSpan = mockSpans.get(0);
Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey()));
// logs
Assert.assertEquals(1, mockSpan.logEntries().size());
Assert.assertEquals(2, mockSpan.logEntries().get(0).fields().size());
Assert.assertEquals(Tags.ERROR.getKey(), mockSpan.logEntries().get(0).fields().get("event"));
Assert.assertNotNull(mockSpan.logEntries().get(0).fields().get("error.object"));
}
开发者ID:opentracing-contrib,项目名称:java-apache-httpclient,代码行数:22,代码来源:TracingHttpClientBuilderTest.java
示例9: postAttempt
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
public static String postAttempt(int id) throws IOException {
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null || StudySettings.getInstance().getUser() == null) return "";
final HttpPost attemptRequest = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.ATTEMPTS);
String attemptRequestBody = new Gson().toJson(new StepicWrappers.AttemptWrapper(id));
attemptRequest.setEntity(new StringEntity(attemptRequestBody, ContentType.APPLICATION_JSON));
final CloseableHttpResponse attemptResponse = client.execute(attemptRequest);
final HttpEntity responseEntity = attemptResponse.getEntity();
final String attemptResponseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
final StatusLine statusLine = attemptResponse.getStatusLine();
EntityUtils.consume(responseEntity);
if (statusLine.getStatusCode() != HttpStatus.SC_CREATED) {
LOG.warn("Failed to make attempt " + attemptResponseString);
return "";
}
return attemptResponseString;
}
示例10: executeHttpPost
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
/**
* Performs HTTP Post request for the end point with the given path, with
* the given JSON as payload.
*
* @param path
* the path to be called.
* @param jsonContent
* the JSON content to be posted.
* @return the CloseableHttpResponse object.
* @throws ClientProtocolException
* @throws IOException
*/
public CloseableHttpResponse executeHttpPost(String path, String jsonContent)
throws ClientProtocolException, IOException {
logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);
HttpPost httpPost = createHttpPost(baseUri + path);
StringEntity input = new StringEntity(jsonContent, StandardCharsets.UTF_8);
input.setContentType(APPLICATION_JSON);
httpPost.setEntity(input);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);
return response;
}
开发者ID:SAP,项目名称:cloud-ariba-discovery-rfx-to-external-marketplace-ext,代码行数:29,代码来源:OpenApisEndpoint.java
示例11: post
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的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;
}
示例12: testHttpRequestGet
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
@Test
public void testHttpRequestGet() throws Exception {
RequestConfig.Builder req = RequestConfig.custom();
req.setConnectTimeout(5000);
req.setConnectionRequestTimeout(5000);
req.setRedirectsEnabled(false);
req.setSocketTimeout(5000);
req.setExpectContinueEnabled(false);
HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
get.setConfig(req.build());
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(5);
HttpClientBuilder builder = HttpClients.custom();
builder.disableAutomaticRetries();
builder.disableRedirectHandling();
builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
builder.setConnectionManager(cm);
CloseableHttpClient client = builder.build();
String s = client.execute(get, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
assertEquals(301, response.getStatusLine().getStatusCode());
return "success";
}
});
assertEquals("success", s);
}
示例13: sendGetCommand
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
/**
* sendGetCommand
*
* @param url
* @param parameters
* @return
*/
public Map<String, String> sendGetCommand(String url, Map<String, Object> parameters)
throws ManagerResponseException {
Map<String, String> response = new HashMap<String, String>();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
try {
CloseableHttpResponse httpResponse = httpclient.execute(httpget, 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;
}
示例14: simpleGet
import org.apache.http.impl.client.CloseableHttpClient; //导入方法依赖的package包/类
/**
* Simple Http Get.
*
* @param path the path
* @return the CloseableHttpResponse
* @throws URISyntaxException the URI syntax exception
* @throws IOException Signals that an I/O exception has occurred.
* @throws MininetException the MininetException
*/
public CloseableHttpResponse simpleGet(String path)
throws URISyntaxException, IOException, MininetException {
URI uri = new URIBuilder()
.setScheme("http")
.setHost(mininetServerIP.toString())
.setPort(mininetServerPort.getPort())
.setPath(path)
.build();
CloseableHttpClient client = HttpClientBuilder.create().build();
RequestConfig config = RequestConfig
.custom()
.setConnectTimeout(CONNECTION_TIMEOUT_MS)
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
.setSocketTimeout(CONNECTION_TIMEOUT_MS)
.build();
HttpGet request = new HttpGet(uri);
request.setConfig(config);
request.addHeader("Content-Type", "application/json");
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() >= 300) {
throw new MininetException(String.format("failure - received a %d for %s.",
response.getStatusLine().getStatusCode(), request.getURI().toString()));
}
return response;
}
示例15: 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