Java Code Examples for org.apache.http.client.methods.CloseableHttpResponse

The following are top voted examples for showing how to use org.apache.http.client.methods.CloseableHttpResponse. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: restheart-java-client   File: HttpConnectionUtils.java   View source code 9 votes vote down vote up
@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;
}
 
Example 2
Project: restheart-java-client   File: HttpConnectionUtils.java   View source code 9 votes vote down vote up
@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;
}
 
Example 3
Project: devops-cstack   File: MonitoringServiceImpl.java   View source code 8 votes vote down vote up
@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;
}
 
Example 4
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View source code 7 votes vote down vote up
/**
 * 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

}
 
Example 5
Project: mumu-core   File: HttpClientUtil.java   View source code 7 votes vote down vote up
/**
 * 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;
}
 
Example 6
Project: Sem-Update   File: VentanaPrincipal.java   View source code 7 votes vote down vote up
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:?]");
    }
 
Example 7
Project: Thrush   File: HttpRequest.java   View source code 7 votes vote down vote up
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;
}
 
Example 8
Project: java-web-services-training   File: Jws1042Application.java   View source code 7 votes vote down vote up
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"));
			}
		}
	}
}
 
Example 9
Project: stock-api-sdk   File: HttpUtilsTest.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 10
Project: cloud-ariba-partner-flow-extension-ext   File: PartnerFlowExtensionApiFacade.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 11
Project: NetDiscovery   File: HttpClientDownloader.java   View source code 6 votes vote down vote up
@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;
        }
    });
}
 
Example 12
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View source code 6 votes vote down vote up
/**
 * 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

}
 
Example 13
Project: PowerApi   File: HttpUtil.java   View source code 6 votes vote down vote up
/**
 * 处理返回结果数据
 *
 * @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();
}
 
Example 14
Project: Wechat-Group   File: SimpleGetRequestExecutor.java   View source code 6 votes vote down vote up
@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();
  }
}
 
Example 15
Project: pyroclast-java   File: PyroclastDeploymentClient.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 16
Project: FCat   File: HttpCallImpl.java   View source code 6 votes vote down vote up
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);
	}
}
 
Example 17
Project: RobotServer   File: HttpService.java   View source code 6 votes vote down vote up
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();
		}
	}
}
 
Example 18
Project: jspider   File: PlainTextResponse.java   View source code 6 votes vote down vote up
@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);
}
 
Example 19
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View source code 6 votes vote down vote up
/**
 * [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;

}
 
Example 20
Project: momo-2   File: WebServer.java   View source code 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 21
Project: swallow-core   File: HttpsUtils.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 22
Project: ibm-cloud-devops   File: PublishSQ.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 23
Project: aws-xray-sdk-java   File: DefaultHttpClient.java   View source code 6 votes vote down vote up
@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();
        }
    }
}
 
Example 24
Project: dubbocloud   File: MockTestFilter.java   View source code 6 votes vote down vote up
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;
}
 
Example 25
Project: cloud-ariba-partner-flow-extension-ext   File: OpenApisEndpoint.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 26
Project: activiti-analytics-spring-boot   File: ElasticHTTPClient.java   View source code 6 votes vote down vote up
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;
	}
 
Example 27
Project: Thrush   File: HttpRequest.java   View source code 6 votes vote down vote up
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;
}
 
Example 28
Project: Thrush   File: HttpRequest.java   View source code 6 votes vote down vote up
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;
}
 
Example 29
Project: Cryptocurrency-Java-Wrappers   File: GoogleTrends.java   View source code 6 votes vote down vote up
/**
 * 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);

}
 
Example 30
Project: devops-cstack   File: RestUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 31
Project: goobi-viewer-connector   File: Utils.java   View source code 6 votes vote down vote up
/**
 * 
 * @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 "";
}
 
Example 32
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View source code 6 votes vote down vote up
/**
 * 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

}
 
Example 33
Project: educational-plugin   File: EduStepicConnector.java   View source code 6 votes vote down vote up
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;
}
 
Example 34
Project: Cable-Android   File: LegacyMmsConnection.java   View source code 6 votes vote down vote up
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");
}
 
Example 35
Project: Wechat-Group   File: QrCodeRequestExecutor.java   View source code 6 votes vote down vote up
@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();
  }

}
 
Example 36
Project: crawler-jsoup-maven   File: HttpUtil.java   View source code 6 votes vote down vote up
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;  
}
 
Example 37
Project: restheart-java-client   File: RestHeartClientApi.java   View source code 6 votes vote down vote up
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;
}
 
Example 38
Project: bboxapi-voicemail   File: VoiceMailApi.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 39
Project: educational-plugin   File: CCStepicConnector.java   View source code 6 votes vote down vote up
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());
    }
  });
}
 
Example 40
Project: cloud-ariba-discovery-rfx-to-external-marketplace-ext   File: PublicSourcingApiFacade.java   View source code 5 votes vote down vote up
/**
 * Retrieves the "count" most recent events from Extension Queue.
 * 
 * @param count
 *            the number of events to be retrieved from the Extension Queue.
 * @return the "count" most recent events from the Extension Queue or null
 *         in case of no events.
 * @throws UnsuccessfulOperationException
 *             when retrieving the events was not successful.
 */
public EventsDto retrieveEvents(int count) throws UnsuccessfulOperationException {
	logger.debug(DEBUG_RETRIEVING_EVENTS_MESSAGE, count);

	EventsDto result = null;
	String retrieveEventsPath = MessageFormat.format(RETRIEVE_EVENTS_PATH, siteId, count);

	logger.debug(DEBUG_CALLING_MESSAGE, retrieveEventsPath);
	try (CloseableHttpResponse retrieveEventsResponse = openApisEndpoint.executeHttpGet(retrieveEventsPath)) {
		int retrieveEventsResponseStatusCode = HttpResponseUtils.validateHttpStatusResponse(retrieveEventsResponse,
				HttpStatus.SC_OK, HttpStatus.SC_NO_CONTENT);

		logger.debug(DEBUG_CALLING_URI_RETURNED_STATUS_MESSAGE, retrieveEventsPath,
				retrieveEventsResponseStatusCode);

		if (retrieveEventsResponseStatusCode == HttpStatus.SC_OK) {
			HttpEntity retrieveEventsResponseEntity = retrieveEventsResponse.getEntity();
			if (retrieveEventsResponseEntity != null) {
				try {
					result = HttpResponseUtils.convertHttpResponse(retrieveEventsResponseEntity, EventsDto.class);
				} finally {
					EntityUtils.consume(retrieveEventsResponseEntity);
				}
			}
		}

	} catch (IOException | HttpResponseException e) {
		String errorMessage = MessageFormat.format(ERROR_PROBLEM_OCCURED_WHILE_CALLING_MESSAGE, retrieveEventsPath);
		logger.error(errorMessage);
		throw new UnsuccessfulOperationException(errorMessage, e);
	}

	logger.debug(DEBUG_EVENTS_RETRIEVED_MESSAGE, result);

	return result;
}