Java 类org.apache.http.client.methods.CloseableHttpResponse 实例源码
项目:restheart-java-client
文件:HttpConnectionUtils.java
@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;
}
项目:Cryptocurrency-Java-Wrappers
文件:Etherscan.java
/**
* 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
}
项目:pyroclast-java
文件:PyroclastDeploymentClient.java
public ReadAggregatesResult readAggregates() throws IOException, PyroclastAPIException {
ensureBaseAttributes();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String url = String.format("%s/%s/aggregates", this.buildEndpoint(), this.deploymentId);
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Authorization", this.readApiKey);
httpGet.addHeader("Content-type", FORMAT);
ReadAggregatesResult result;
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
ResponseParser<ReadAggregatesResult> parser = new ReadAggregatesParser();
result = parser.parseResponse(response, MAPPER);
}
return result;
}
}
项目:logviewer
文件:GistCreator.java
/**
* Call the API to create gist and return the http url if any
*/
private String callGistApi(String gistJson, GistListener listener) {
try {
CloseableHttpClient httpclient = createDefault();
HttpPost httpPost = new HttpPost(GIST_API);
httpPost.setHeader("Accept", "application/vnd.github.v3+json");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(gistJson, ContentType.APPLICATION_JSON));
CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
JsonObject result = (JsonObject) new JsonParser().parse(EntityUtils.toString(responseEntity));
EntityUtils.consume(responseEntity);
response.close();
httpclient.close();
return result.getAsJsonPrimitive("html_url").getAsString();
} catch (Exception ex) {
}
return null;
}
项目:Sem-Update
文件:VentanaPrincipal.java
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:?]");
}
项目:devops-cstack
文件:MonitoringServiceImpl.java
@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;
}
项目:java-web-services-training
文件:Jws1042Application.java
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"));
}
}
}
}
项目:mumu-core
文件:HttpClientUtil.java
/**
* 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;
}
项目:cloud-ariba-partner-flow-extension-ext
文件:PartnerFlowExtensionApiFacade.java
/**
* 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);
}
项目:NetDiscovery
文件:HttpClientDownloader.java
@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;
}
});
}
项目:Cryptocurrency-Java-Wrappers
文件:Etherscan.java
/**
* 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
}
项目:PowerApi
文件:HttpUtil.java
/**
* 处理返回结果数据
*
* @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();
}
项目:Wechat-Group
文件:SimpleGetRequestExecutor.java
@Override
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException {
if (queryParam != null) {
if (uri.indexOf('?') == -1) {
uri += '?';
}
uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
}
HttpGet httpGet = new HttpGet(uri);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpGet.setConfig(config);
}
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
return responseContent;
} finally {
httpGet.releaseConnection();
}
}
项目:FCat
文件:HttpCallImpl.java
private CloseableHttpResponse getGetResponse(String apiUrl, HttpGet httpGet) throws IllegalStateException {
localContext.setCookieStore(cookieStore);
try {
httpGet.setURI(new URI(apiUrl));
if (reqHeader != null) {
Iterator<String> iterator = reqHeader.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
httpGet.addHeader(key, reqHeader.get(key));
}
}
return httpclient.execute(httpGet, localContext);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
项目:RobotServer
文件:HttpService.java
private String httpPost(String postUrl, String postData, String contentType) throws ClientProtocolException,
IOException {
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(postUrl);
StringEntity entity = new StringEntity(postData, UTF8);
entity.setContentType(contentType);
post.setEntity(entity);
response = getHttpClient().execute(post);
return EntityUtils.toString(response.getEntity(), UTF8);
} finally {
if (null != response) {
response.close();
}
}
}
项目:jspider
文件:PlainTextResponse.java
@Override
protected String handleHttpResponseResult(CloseableHttpResponse httpResponse) throws Throwable {
if (StringUtils.isNotBlank(charset)) {
return IOUtils.toString(httpResponse.getEntity().getContent(), charset);
}
Charset contentTypeCharset = getCharsetFromContentType(httpResponse.getEntity());
if (contentTypeCharset != null) {
return IOUtils.toString(httpResponse.getEntity().getContent(), contentTypeCharset.name());
}
byte[] bytes = IOUtils.toByteArray(httpResponse.getEntity().getContent());
String content = new String(bytes, Config.DEFAULT_CHARSET);
Charset contentCharset = getCharsetFromContent(content);
if (contentCharset == null || contentCharset.name().equalsIgnoreCase(Config.DEFAULT_CHARSET)) {
return content;
}
return new String(bytes, contentCharset);
}
项目:Cryptocurrency-Java-Wrappers
文件:Etherscan.java
/**
* [BETA] Check Contract Execution Status (if there was an error during contract execution)
* @param txHash Transaction hash
* @return Contract execution status. isError:0 = pass , isError:1 = error during contract execution
*/
public ContractExecutionStatus checkContractExecutionStatus(String txHash) {
HttpGet get = new HttpGet(PUBLIC_URL + "?module=transaction&action=getstatus&txhash=" + txHash + "&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);
ContractExecutionStatus current = new ContractExecutionStatus();
for(int j = 0; j < a.size(); j++)
current.addData(a.get(j));
return current;
}
项目:momo-2
文件:WebServer.java
/**
* Perform an Oauth2 callback to the Discord servers with the token given by the user's approval
* @param token Token from user
* @param res Passed on response
* @throws ClientProtocolException Error in HTTP protocol
* @throws IOException Encoding exception or error in protocol
* @throws NoAPIKeyException No API keys set
*/
static void oauth(String token, Response res) throws ClientProtocolException, IOException, NoAPIKeyException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost("https://discordapp.com/api/oauth2/token");
List<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("client_id", Bot.getInstance().getApiKeys().get("dashboardid")));
nvp.add(new BasicNameValuePair("client_secret", Bot.getInstance().getApiKeys().get("dashboardsecret")));
nvp.add(new BasicNameValuePair("grant_type", "authorization_code"));
nvp.add(new BasicNameValuePair("code", token));
post.setEntity(new UrlEncodedFormEntity(nvp));
String accessToken;
CloseableHttpResponse response = httpclient.execute(post);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
JsonObject authJson;
try(BufferedReader buffer = new BufferedReader(new InputStreamReader(entity.getContent()))) {
authJson = Json.parse(buffer.lines().collect(Collectors.joining("\n"))).asObject();
}
accessToken = authJson.getString("access_token", "");
EntityUtils.consume(entity);
getGuilds(res, accessToken);
} finally {
response.close();
}
}
项目:swallow-core
文件:HttpsUtils.java
/**
* post方式,xml格式的参数发起请求,并将响应结果转为SwallowHttpRequestResult
*
* @param url 请求URL
* @param xml xml格式数据
* @return SwallowHttpRequestResult
* @throws SwallowException SwallowException
*/
public static SwallowHttpResponse postXml(String url, String xml) throws SwallowException {
CloseableHttpClient httpClient = getCloseableHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HttpConstant.CONTENT_TYPE, HttpConstant.TEXT_XML_VALUE);
httpPost.setEntity(new StringEntity(xml, CharsetConstant.UTF8));
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
return new SwallowHttpResponse(EntityUtils.toString(response.getEntity(), CharsetConstant.UTF8));
} catch (IOException e) {
throw new SwallowException("执行 HTTPS 请求异常!", e);
} finally {
close(httpClient, response);
}
}
项目:ibm-cloud-devops
文件:PublishSQ.java
/**
* Sends a GET request to the provided url
*
* @param url the endpoint of the request
* @param headers a map of headers where key is the header name and the map value is the header value
* @return a JSON parsed representation of the payload returneds
* @throws Exception
*/
private JsonObject sendGETRequest(String url, Map<String, String> headers) throws Exception {
String resStr;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet getMethod = new HttpGet(url);
getMethod = addProxyInformation(getMethod);
//add request headers
for(Map.Entry<String, String> entry: headers.entrySet()) {
getMethod.setHeader(entry.getKey(), entry.getValue());
}
CloseableHttpResponse response = httpClient.execute(getMethod);
resStr = EntityUtils.toString(response.getEntity());
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(resStr);
JsonObject resJson = element.getAsJsonObject();
return resJson;
}
项目:aws-xray-sdk-java
文件:DefaultHttpClient.java
@Override
public CloseableHttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException {
Subsegment subsegment = getRecorder().beginSubsegment(TracedHttpClient.determineTarget(request).getHostName());
try {
if (null != subsegment) {
TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request));
}
CloseableHttpResponse response = super.execute(request, context);
if (null != subsegment) {
TracedResponseHandler.addResponseInformation(subsegment, response);
}
return response;
} catch (Exception e) {
if (null != subsegment) {
subsegment.addException(e);
}
throw e;
} finally {
if (null != subsegment) {
getRecorder().endSubsegment();
}
}
}
项目:dubbocloud
文件:MockTestFilter.java
private String post(String url, List<NameValuePair> nvps) throws IOException{
CloseableHttpClient httpclient = connectionPoolManage.getHttpClient();
HttpPost httpPost = new HttpPost(url);
if(nvps != null)
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpPost);
String result = null;
if(response.getStatusLine().getStatusCode() == 200){
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}
httpclient.close();
return result;
}
项目:cloud-ariba-partner-flow-extension-ext
文件:OpenApisEndpoint.java
/**
* Performs HTTP Get request with OAuth authentication for the endpoint with
* the given path with the given HTTP headers.
*
* @param path
* the path to be called.
* @param headers
* map with HTTP header names and values to be included in the
* request.
* @return the CloseableHttpResponse object.
* @throws ClientProtocolException
* @throws IOException
*/
CloseableHttpResponse executeHttpGet(String path, Map<String, String> headers)
throws ClientProtocolException, IOException {
logger.debug(DEBUG_EXECUTING_HTTP_GET_FOR, baseUri, path);
HttpGet httpGet = createHttpGet(baseUri + path);
for (String header : headers.keySet()) {
httpGet.addHeader(header, headers.get(header));
}
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpGet);
logger.debug(DEBUG_EXECUTED_HTTP_GET_FOR, baseUri, path);
return response;
}
项目:Thrush
文件:HttpRequest.java
public static String authClient() {
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.authClient);
httpPost.addHeader(CookieManager.cookieHeader());
String param = Optional.ofNullable(ResultManager.get("tk")).map(r -> null == r.getValue() ? StringUtils.EMPTY : r.getValue().toString()).orElse(StringUtils.EMPTY);
httpPost.setEntity(new StringEntity("tk=" + param, ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));
String result = StringUtils.EMPTY;
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
result = EntityUtils.toString(response.getEntity());
CookieManager.touch(response);
} catch (IOException e) {
logger.error("authClient error", e);
}
return result;
}
项目:activiti-analytics-spring-boot
文件:ElasticHTTPClient.java
protected HttpResponse executeHttpRequest(HttpRequestBase httpRequest, String method) {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpRequest);
} catch (IOException e) {
throw new ActivitiException("error while executing http request: " + method + " " + httpRequest.getURI(),
e);
}
if (response.getStatusLine().getStatusCode() >= 400) {
throw new ActivitiException("error while executing http request " + method + " " + httpRequest.getURI()
+ " with status code: " + response.getStatusLine().getStatusCode());
}
return response;
}
项目:Thrush
文件:HttpRequest.java
public static String ticketQuery(TrainQuery trainQuery) {
Objects.requireNonNull(trainQuery);
CloseableHttpClient httpClient = buildHttpClient();
HttpGet httpGet = new HttpGet(UrlConfig.ticketQuery + "?" + genQueryParam(trainQuery));
httpGet.setHeader(CookieManager.cookieHeader());
String result = StringUtils.EMPTY;
try(CloseableHttpResponse response = httpClient.execute(httpGet)) {
CookieManager.touch(response);
result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
logger.error("ticketQuery error", e);
}
return result;
}
项目:Thrush
文件:HttpRequest.java
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;
}
项目:Thrush
文件:HttpRequest.java
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;
}
项目:Cryptocurrency-Java-Wrappers
文件:GoogleTrends.java
/**
* Get trend data; interval is in months. Up to five keywords may be entered. Calling this frequently will result in denied query
* @param keywords Keywords to query. Up to five may be queried at a time
* @param startDate Start date. Format is in "mm/yyyy"
* @param deltaMonths Time, in months, from start date for which to retrieve data
* @return Trend data
*/
public static Trend getTrend(String[] keywords, String startDate, int deltaMonths) {
StringBuilder sb = new StringBuilder();
sb.append(PUBLIC_URL);
StringBuilder param_q = new StringBuilder();
for(String each : keywords) {
param_q.append(each);
param_q.append(',');
}
param_q.setLength(param_q.length()-1);
append(sb, "q", param_q.toString());
append(sb, "cid", "TIMESERIES_GRAPH_0");
append(sb, "export", "3");
append(sb, "date", startDate + "+" + deltaMonths + "m");
append(sb, "hl", "en-US");
HttpPost post = new HttpPost(sb.toString());
post.addHeader("Cookie", cookieString);
String response = null;
try(CloseableHttpResponse httpResponse = httpClient.execute(post)) {
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
} catch (IOException e) {
e.printStackTrace();
}
return parseResponse(response, keywords);
}
项目:devops-cstack
文件:RestUtils.java
public Map<String, String> sendGetFileCommand(String url, String filePath, 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);
InputStream inputStream = httpResponse.getEntity().getContent();
FileOutputStream fos = new FileOutputStream(new File(filePath));
int inByte;
while ((inByte = inputStream.read()) != -1)
fos.write(inByte);
inputStream.close();
fos.close();
httpResponse.close();
} catch (Exception e) {
throw new ManagerResponseException(e.getMessage(), e);
}
return response;
}
项目:goobi-viewer-connector
文件:Utils.java
/**
*
* @param url
* @return
* @throws IOException
* @throws UnsupportedOperationException
*/
public static String getWebContent(String url) throws UnsupportedOperationException, IOException {
logger.trace("getWebContent: {}", url);
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(HTTP_TIMEOUT).setConnectTimeout(HTTP_TIMEOUT)
.setConnectionRequestTimeout(HTTP_TIMEOUT).build();
try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build()) {
HttpGet get = new HttpGet(url);
Charset chars = Charset.forName(DEFAULT_ENCODING);
try (CloseableHttpResponse response = httpClient.execute(get); StringWriter writer = new StringWriter()) {
int code = response.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_OK) {
logger.trace("{}: {}", code, response.getStatusLine().getReasonPhrase());
IOUtils.copy(response.getEntity().getContent(), writer);
return writer.toString();
}
logger.trace("{}: {}", code, response.getStatusLine().getReasonPhrase());
}
}
return "";
}
项目:Cryptocurrency-Java-Wrappers
文件:Etherscan.java
/**
* Get ERC20-Token account balance by contract address
* @param contractAddress Contract address
* @param address Address
* @return ERC29-Token account balance
*/
public BigInteger getErc20TokenAccountBalance(String contractAddress, String address) {
HttpGet get = new HttpGet(PUBLIC_URL + "?module=account&action=tokenbalance&contractaddress=" + contractAddress + "&address=" + address + "&tag=latest" + "&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
}
项目:educational-plugin
文件:EduStepicConnector.java
public static boolean enrollToCourse(final int courseId, @Nullable final StepicUser stepicUser) {
if (stepicUser == null) return false;
HttpPost post = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.ENROLLMENTS);
try {
final StepicWrappers.EnrollmentWrapper enrollment = new StepicWrappers.EnrollmentWrapper(String.valueOf(courseId));
post.setEntity(new StringEntity(new GsonBuilder().create().toJson(enrollment)));
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient(stepicUser);
CloseableHttpResponse response = client.execute(post);
StatusLine line = response.getStatusLine();
return line.getStatusCode() == HttpStatus.SC_CREATED;
}
catch (IOException e) {
LOG.warn(e.getMessage());
}
return false;
}
项目:Cable-Android
文件:LegacyMmsConnection.java
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");
}
项目:Wechat-Group
文件:QrCodeRequestExecutor.java
@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();
}
}
项目:crawler-jsoup-maven
文件:HttpUtil.java
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;
}
项目:restheart-java-client
文件:HttpConnectionUtils.java
@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;
}
项目:restheart-java-client
文件:RestHeartClientApi.java
private RestHeartClientResponse extractFromResponse(final CloseableHttpResponse httpResponse) {
RestHeartClientResponse response = null;
JsonObject responseObj = null;
if (httpResponse != null) {
StatusLine statusLine = httpResponse.getStatusLine();
Header[] allHeaders = httpResponse.getAllHeaders();
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
try {
String responseStr = IOUtils.toString(resEntity.getContent(), "UTF-8");
if (responseStr != null && !responseStr.isEmpty()) {
JsonParser parser = new JsonParser();
responseObj = parser.parse(responseStr).getAsJsonObject();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Was unable to extract response body", e);
}
}
response = new RestHeartClientResponse(statusLine, allHeaders, responseObj);
}
return response;
}
项目:bboxapi-voicemail
文件:VoiceMailApi.java
/**
* Execute http request.
*
* @param request
* @return
*/
private HttpResponse executeRequest(HttpRequestBase request) {
CloseableHttpResponse response;
try {
response = mHttpClient.execute(request);
try {
return response;
} finally {
response.close();
}
} catch (IOException e) {
//ignored
}
return null;
}
项目:educational-plugin
文件:CCStepicConnector.java
public static void deleteTask(@NotNull final Integer task, Project project) {
final HttpDelete request = new HttpDelete(EduStepicNames.STEPIC_API_URL + EduStepicNames.STEP_SOURCES + task);
ApplicationManager.getApplication().invokeLater(() -> {
try {
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null) return;
final CloseableHttpResponse response = client.execute(request);
final HttpEntity responseEntity = response.getEntity();
final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
EntityUtils.consume(responseEntity);
final StatusLine line = response.getStatusLine();
if (line.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
LOG.error("Failed to delete task " + responseString);
showErrorNotification(project, "Failed to delete task ", responseString);
}
}
catch (IOException e) {
LOG.error(e.getMessage());
}
});
}