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 10 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: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View source code 8 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 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: Thrush   File: HttpRequest.java   View source code 8 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 5
Project: restheart-java-client   File: HttpConnectionUtils.java   View source code 8 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 6
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 7
Project: PowerApi   File: HttpUtil.java   View source code 7 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 8
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 9
Project: Thrush   File: HttpRequest.java   View source code 7 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 10
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 11
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 12
Project: instagram4j   File: InstagramDirectShareRequest.java   View source code 6 votes vote down vote up
@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;
	}
}
 
Example 13
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 14
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 15
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 16
Project: Cryptocurrency-Java-Wrappers   File: Poloniex.java   View source code 6 votes vote down vote up
/**
 * @return Order book for all markets, as well as a sequence number for use with the Push API and an indicator specifying whether the market is frozen
 */
public static OrderBook[] orderBookAll() {

	HttpGet get = new HttpGet(PUBLIC_URL + "?command=returnOrderBook&currencyPair=all");
	String response = null;

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

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

	ArrayList<OrderBook> orderBookDatas = new ArrayList<>();

	ArrayList<OrderBook.Order> asks = new ArrayList<>();
	ArrayList<OrderBook.Order> bids = new ArrayList<>();

	boolean asksDoneParsing = false;

	for(@SuppressWarnings("rawtypes") CustomNameValuePair<String, CustomNameValuePair> each : a) {

		if(each.getName().equals("asks"))
			asksDoneParsing = false;
		else if(each.getName().equals("bids"))
			asksDoneParsing = true;
		else if(each.getName().equals("isFrozen"))
			orderBookDatas.get(orderBookDatas.size()-1).isFrozen = Boolean.parseBoolean(each.getValue().toString());
		else if(each.getName().equals("seq"))
			orderBookDatas.get(orderBookDatas.size()-1).seq = Long.parseLong(each.getValue().toString());
		else if(each.getValue() == null) {
			orderBookDatas.add(new OrderBook(each.getName()));
		} else {
			OrderBook.Order order = new OrderBook.Order(
					Double.parseDouble(each.getName().toString()),
					Double.parseDouble(each.getValue().toString()));
			if(!asksDoneParsing) {
				asks.add(order);
				if(orderBookDatas.get(orderBookDatas.size()-1).asks == null)
					orderBookDatas.get(orderBookDatas.size()-1).asks = new ArrayList<>();
				orderBookDatas.get(orderBookDatas.size()-1).asks.add(order);
			} else {
				bids.add(order);
				if(orderBookDatas.get(orderBookDatas.size()-1).bids == null)
					orderBookDatas.get(orderBookDatas.size()-1).bids = new ArrayList<>();
				orderBookDatas.get(orderBookDatas.size()-1).bids.add(order);
			}
		}
	}

	return orderBookDatas.toArray(new OrderBook[orderBookDatas.size()]);

}
 
Example 17
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 18
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 19
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 20
Project: cloud-ariba-partner-flow-extension-ext   File: PartnerFlowExtensionApiFacade.java   View source code 6 votes vote down vote up
/**
 * Retrieves event data.
 * 
 * @param eventId
 *            event id which data will be retrieved
 * @return event data.
 * @throws UnsuccessfulOperationException
 */
public AsnDataDto retrieveEventData(String eventId) throws UnsuccessfulOperationException {
	AsnDataDto result = null;

	String retrieveEventDataPath = MessageFormat.format(RETRIEVE_EVENT_DATA_PATH, flowExtensionId, eventId);

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

	logger.debug(DEBUG_CALLING_URI_MESSAGE, retrieveEventDataPath);
	try (CloseableHttpResponse retrieveEventDataResponse = openApiEndpoint.executeHttpGet(retrieveEventDataPath,
			headers)) {
		int retrieveEventDataResponseStatusCode = HttpResponseUtils
				.validateHttpStatusResponse(retrieveEventDataResponse, HttpStatus.SC_OK);
		logger.debug(DEBUG_CALLING_URI_RETURNED_STATUS_MESSAGE, retrieveEventDataPath,
				retrieveEventDataResponseStatusCode);

		HttpEntity retrieveEventDataResponseEntity = retrieveEventDataResponse.getEntity();
		if (retrieveEventDataResponseEntity != null) {
			try {
				result = HttpResponseUtils.deserialize(retrieveEventDataResponseEntity, AsnDataDto.class);
			} finally {
				EntityUtils.consume(retrieveEventDataResponseEntity);
			}
		}
	} catch (IOException | HttpResponseException e) {
		String errorMessage = MessageFormat.format(ERROR_PROBLEM_OCCURED_WHILE_CALLING_URI_MESSAGE,
				retrieveEventDataPath);
		logger.error(errorMessage);
		throw new UnsuccessfulOperationException(errorMessage, e);
	}

	logger.debug(DEBUG_CALLED_URI_SUCCESSFULLY_MESSAGE, retrieveEventDataPath);

	return result;
}
 
Example 21
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 22
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 23
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 24
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 25
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 26
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 27
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 28
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 29
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 30
Project: logviewer   File: GistCreator.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 31
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 32
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 33
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 34
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 35
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 36
Project: InComb   File: TxtContentReader.java   View source code 6 votes vote down vote up
/**
 * Returns the content read form content-source.
 * @return read {@link Content}
 */
@Override
public Content[] read(final FetchHistory lastFetch) {

	final CloseableHttpClient httpClient = HttpClients.createDefault();
	final HttpGet httpget = new HttpGet(contentSource.getUrl());
	final HttpContext context = new BasicHttpContext();

	CloseableHttpResponse response = null;
	String stringRead = null;

	try {
		try {
			LOGGER.info("Loading uri: " + httpget.getURI());
			response = httpClient.execute(httpget, context);
			final HttpEntity entity = response.getEntity();

			if (entity != null) {
				stringRead = IOUtils.toString(entity.getContent());
				LOGGER.info("Read {} bytes from: {}", stringRead.getBytes().length, httpget.getURI());
			}

		} finally {
			CloseUtil.close(response);
			CloseUtil.close(httpClient);
		}

	} catch (final Exception e) {
		LOGGER.warn("Error occurred while reading text document: " + contentSource.getUrl());
	}

	return new Content[] { createContentObject(stringRead) };
}
 
Example 37
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 38
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 39
Project: educational-plugin   File: EduStepicClient.java   View source code 6 votes vote down vote up
static <T> T getFromStepic(String link, final Class<T> container, @NotNull final CloseableHttpClient client) throws IOException {
  if (!link.startsWith("/")) link = "/" + link;
  final HttpGet request = new HttpGet(EduStepicNames.STEPIC_API_URL + link);

  final CloseableHttpResponse response = client.execute(request);
  final StatusLine statusLine = response.getStatusLine();
  final HttpEntity responseEntity = response.getEntity();
  final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
  EntityUtils.consume(responseEntity);
  if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
    throw new IOException("Stepic returned non 200 status code " + responseString);
  }
  return deserializeStepicResponse(container, responseString);
}
 
Example 40
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");
}