Java Code Examples for org.apache.http.util.EntityUtils.toString()

The following are Jave code examples for showing how to use toString() of the org.apache.http.util.EntityUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: dooo   File: OpenClient.java   View Source Code Vote up 8 votes
private static String execute0(HttpUriRequest httpUriRequest) throws Exception {
    CloseableHttpResponse closeableHttpResponse = null;

    String var4;
    try {
        closeableHttpResponse = closeableHttpClient.execute(httpUriRequest);
        String response = EntityUtils.toString(closeableHttpResponse.getEntity(), CHARSET);
        var4 = response;
    } catch (Exception var7) {
        throw var7;
    } finally {
        CloseUtils.close(closeableHttpResponse);
    }

    return var4;
}
 
Example 2
Project: asch-java   File: REST.java   View Source Code Vote up 7 votes
protected static String getResponseContent(HttpResponse response) throws IOException{

            if (null == response)
                throw new IOException("Get response failed");

            String content = EntityUtils.toString(response.getEntity());

            if (logger.isDebugEnabled()) {
                logger.debug(String.format("RESPONSE code:%d, reason:%s, content:%s", response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase(),
                        content));
            }

            if (!content.contains("\"success\":")){
                throw new IOException(String.format("Http server response failed, code:%d, reason:%s.\n content:%s",
                        response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase(),
                        content));
            }

            return content;
        }
 
Example 3
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View Source Code Vote up 7 votes
/**
 * 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 4
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View Source Code Vote up 7 votes
/**
 * Returns information about a transaction by block number and transaction index position
 * @param blockNumber Block number
 * @param index Index
 * @return Transaction information
 */
public Transaction transactionByBlockNumberAndIndex(BigInteger blockNumber, BigInteger index) {

	HttpGet get = new HttpGet(PUBLIC_URL + "?module=proxy&action=eth_getTransactionByBlockNumberAndIndex&tag=" + "0x" + blockNumber.toString(16) + "&index=" + "0x" + index.toString(16) + "&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);

	Transaction current = new Transaction();

	for(int j = 0; j < a.size(); j++)
		current.addData(a.get(j));

	return current;

}
 
Example 5
Project: financisto1-holo   File: HttpClientWrapper.java   View Source Code Vote up 7 votes
public String getAsString(String url) throws Exception {
    HttpGet get = new HttpGet(url);
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.handle-redirects",false);
    get.setParams(params);
    HttpResponse r = httpClient.execute(get);
    return EntityUtils.toString(r.getEntity());
}
 
Example 6
Project: HttpClientMock   File: BodyMatcher.java   View Source Code Vote up 6 votes
@Override
public boolean matches(Request request) {
    try {
        HttpEntity entity = ((HttpEntityEnclosingRequestBase) request.getHttpRequest()).getEntity();
        if (entity == null) {
            return false;
        }
        String message = EntityUtils.toString(entity);
        return matcher.matches(message);
    } catch (IOException e) {
        return false;
    }
}
 
Example 7
Project: boohee_v5.6   File: LEYUApplication.java   View Source Code Vote up 6 votes
private String GetDate(String url) {
    String resultString = "";
    try {
        return EntityUtils.toString(new DefaultHttpClient().execute(new HttpGet(wwwhost +
                url)).getEntity());
    } catch (Exception e) {
        this._callback.onFailed(e.getMessage());
        return resultString;
    }
}
 
Example 8
Project: pjbank-java-sdk   File: Credenciamento.java   View Source Code Vote up 6 votes
/**
 * Retorna os dados cadastrais referentes à credencial informada para conta digital
 * @param credencial: Conjunto de credencial e chave para a conta que deseja consultar
 * @return Cliente: Dados cadastrais da credencial informada
 */
public Cliente get(Credencial credencial)
        throws IOException, PJBankException {
    PJBankClient client = new PJBankClient(this.endPoint.concat("/").concat(credencial.getCredencial()));
    HttpGet httpGet = client.getHttpGetClient();
    httpGet.addHeader("x-chave-conta", credencial.getChave());

    String response = EntityUtils.toString(client.doRequest(httpGet).getEntity());

    JSONObject responseObject = new JSONObject(response);

    Cliente cliente = new Cliente();
    cliente.setNome(responseObject.getString("nome_empresa"));
    cliente.setCpfCnpj(responseObject.getString("cnpj"));

    Endereco endereco = new Endereco();
    endereco.setLogradouro(responseObject.getString("endereco"));
    endereco.setNumero(responseObject.getInt("numero"));
    endereco.setComplemento(responseObject.getString("complemento"));
    endereco.setBairro(responseObject.getString("bairro"));
    endereco.setCidade(responseObject.getString("cidade"));
    endereco.setEstado(responseObject.getString("estado"));
    endereco.setCep(responseObject.getString("cep"));

    cliente.setEndereco(endereco);

    String telefone = responseObject.getString("telefone");
    cliente.setDdd(Integer.parseInt(telefone.substring(0, 2)));
    cliente.setTelefone(Long.parseLong(telefone.substring(2, telefone.length())));

    cliente.setEmail(responseObject.getString("email"));
    cliente.setStatus("ativa".equalsIgnoreCase(responseObject.getString("status")));

    return cliente;
}
 
Example 9
Project: sling-org-apache-sling-testing-clients   File: SlingHttpResponse.java   View Source Code Vote up 6 votes
/**
 * <p>Get the {@code String} content of the response.</p>
 * <p>The content is cached so it is safe to call this method several times.</p>
 * <p><b>Attention!</b> Calling this method consumes the entity, so it cannot be used as an InputStream later</p>
 *
 * @return the content as String
 */
public String getContent() {
    if (!this.isConsumed()) {
        try {
            this.content = EntityUtils.toString(this.getEntity());
            this.close();
        } catch (IOException e) {
            throw new RuntimeException("Could not read content from response", e);
        }
    }

    return content;
}
 
Example 10
Project: Equella   File: OAuthTest.java   View Source Code Vote up 6 votes
@Test(enabled = false)
public void testOAuthWithTokenLogin() throws Exception
{
	HttpResponse response = defaultClientTokenRequest("token",
		TokenSecurity.createSecureToken("AutoTest", "token", "token", null));
	String string = EntityUtils.toString(response.getEntity());

	Assert.assertTrue(string.contains("oal_allowButton"), "Should be logged in");

	response = defaultClientTokenRequestPost("event__", "oal.allowAccess");
	Assert.assertTrue(hasAccessToken(response));

	// we should be able to make REST calls with this token as the AutoTest
	// user
}
 
Example 11
Project: TinyURL   File: TinyURLServiceTest.java   View Source Code Vote up 6 votes
@Test
public void testGetURL() throws ClientProtocolException, IOException {
	String shortURL = "ba";
	HttpUriRequest request = new HttpGet("http://localhost:8080/TinyURL/details/" + shortURL);
	HttpResponse response = HttpClientBuilder.create().build().execute(request);
	
	HttpEntity entity = response.getEntity();
	String responseString = EntityUtils.toString(entity, "UTF-8");
	System.out.println(responseString);
	//fail("Not yet implemented");
}
 
Example 12
Project: LearningSummary   File: HttpRequestUtil.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws ParseException, IOException {
	HttpRequestUtil util = new HttpRequestUtil();
	CloseableHttpClient client = util.setDoubleInit();
	
	Map<String,String> map = new HashMap<>();
	CloseableHttpResponse httpPost = util.httpPost(client, "https://127.0.0.1:8443/pwp-web/login.do", map);
	
	HttpEntity entity = httpPost.getEntity();
	String string = EntityUtils.toString(entity, Charset.defaultCharset());
	
	System.out.println(string);
}
 
Example 13
Project: educational-plugin   File: EduAdaptiveStepicConnector.java   View Source Code Vote up 6 votes
public static boolean postRecommendationReaction(@NotNull String lessonId, @NotNull String user, int reaction) {
  final HttpPost post = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.RECOMMENDATION_REACTIONS_URL);
  final String json = new Gson()
    .toJson(new StepicWrappers.RecommendationReactionWrapper(new StepicWrappers.RecommendationReaction(reaction, user, lessonId)));
  post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
  final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
  if (client == null) return false;
  setTimeout(post);
  try {
    final CloseableHttpResponse execute = client.execute(post);
    final int statusCode = execute.getStatusLine().getStatusCode();
    final HttpEntity entity = execute.getEntity();
    final String entityString = EntityUtils.toString(entity);
    EntityUtils.consume(entity);
    if (statusCode == HttpStatus.SC_CREATED) {
      return true;
    }
    else {
      LOG.warn("Stepic returned non-201 status code: " + statusCode + " " + entityString);
      return false;
    }
  }
  catch (IOException e) {
    LOG.warn(e.getMessage());
    return false;
  }
}
 
Example 14
Project: datax   File: HttpClientUtil.java   View Source Code Vote up 6 votes
public String executeAndGet(HttpRequestBase httpRequestBase) throws Exception {
    HttpResponse response;
    String entiStr = "";
    try {
        response = httpClient.execute(httpRequestBase);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            System.err.println("请求地址:" + httpRequestBase.getURI() + ", 请求方法:" + httpRequestBase.getMethod()
                    + ",STATUS CODE = " + response.getStatusLine().getStatusCode());
            if (httpRequestBase != null) {
                httpRequestBase.abort();
            }
            throw new Exception("Response Status Code : " + response.getStatusLine().getStatusCode());
        } else {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                entiStr = EntityUtils.toString(entity, Consts.UTF_8);
            } else {
                throw new Exception("Response Entity Is Null");
            }
        }
    } catch (Exception e) {
        throw e;
    }

    return entiStr;
}
 
Example 15
Project: message-broker   File: ConsumersRestApiTest.java   View Source Code Vote up 5 votes
@Parameters({"admin-username", "admin-password", "broker-hostname", "broker-port"})
@Test
public void testSpecificConsumerRetrieval(String username, String password,
                                          String hostname, String port) throws Exception {
    String queueName = "testSpecificConsumerRetrieval";

    // Create a durable queue using a JMS client
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(username, password, hostname, port)
            .withQueue(queueName)
            .build();

    QueueConnectionFactory connectionFactory
            = (QueueConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    QueueConnection connection = connectionFactory.createQueueConnection();
    connection.start();

    QueueSession queueSession = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    Queue queue = queueSession.createQueue(queueName);
    QueueReceiver receiver = queueSession.createReceiver(queue);

    HttpGet getAllConsumers = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH
                                          + "/" + queueName + "/consumers");

    CloseableHttpResponse response = client.execute(getAllConsumers);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
    String body = EntityUtils.toString(response.getEntity());

    ConsumerMetadata[] consumers = objectMapper.readValue(body, ConsumerMetadata[].class);

    Assert.assertTrue(consumers.length > 0, "Number of consumers returned is incorrect.");

    int id = consumers[0].getId();
    HttpGet getConsumer = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH + "/"
                                              + queueName + "/consumers/" + id);

    response = client.execute(getConsumer);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
    String consumerString = EntityUtils.toString(response.getEntity());
    ConsumerMetadata consumerMetadata = objectMapper.readValue(consumerString, ConsumerMetadata.class);

    Assert.assertEquals(consumerMetadata.getId().intValue(), id, "incorrect message id");

    receiver.close();
    queueSession.close();
    connection.close();
}
 
Example 16
Project: Cryptocurrency-Java-Wrappers   File: Poloniex.java   View Source Code Vote up 5 votes
/**
 * @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: instagram4j   File: InstagramDirectShareRequest.java   View Source Code Vote up 5 votes
@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 18
Project: bubble2   File: ResponseWrap.java   View Source Code Vote up 4 votes
/**
 * 获取响应内容为String
 * 
 * 
 * @date 2015年7月17日
 * @param defaultCharset
 *            指定编码
 * @return
 */
public String getString(Charset defaultCharset) {
	try {
		return EntityUtils.toString(entity, defaultCharset);
	} catch (ParseException | IOException e) {
		logger.error(e.getMessage(), e);
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 19
Project: RobotServer   File: HttpService.java   View Source Code Vote up 4 votes
private String httpPost(String postUrl, Map<String, String> paramMap) throws ClientProtocolException, IOException {
	CloseableHttpResponse response = null;
	try {
		HttpPost post = new HttpPost(postUrl);
		HttpEntity entity = new UrlEncodedFormEntity(getNameValuePairs(paramMap), UTF8);
		post.setEntity(entity);
		response = getHttpClient().execute(post);
		return EntityUtils.toString(response.getEntity(), UTF8);
	} finally {
		if (null != response) {
			response.close();
		}
	}
}
 
Example 20
Project: stock-api-sdk   File: ApiUtils.java   View Source Code Vote up 3 votes
/**
 * Executes POST Http request to an endpoint with provided request post body
 * and headers.
 *
 * @param uri
 *            Endpoint which needs to be hit
 * @param headers
 *            map of headers and their corresponding values
 * @param postData
 *            request body data in byte array
 * @param contentType
 *            content type of request body data like json, xml etc
 * @return return response body as string after executing POST
 * @throws StockException
 *             if api doesn't return with success code or when null/empty
 *             endpoint is passed in uri
 */
public static String doPost(final String uri,
        final Map<String, String> headers, final byte[] postData,
        final ContentType contentType) throws StockException {
    if (sHttpClient == null) {
        sHttpClient = HttpUtils.initialize();
    }

    HttpResponse response = null;
    String responseBody = null;

    if (uri == null || uri.isEmpty()) {
        throw new StockException(-1, "URI cannot be null or Empty");
    }

    HttpPost request = new HttpPost(uri);

    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            request.setHeader(entry.getKey(), entry.getValue());
        }
    }

    try {

        if (postData != null) {
            ByteArrayEntity entity = new ByteArrayEntity(postData,
                    contentType);
            request.setEntity(entity);
        }
        response = sHttpClient.execute(request);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || response.getStatusLine().getStatusCode()
                    == HttpStatus.SC_CREATED) {
            responseBody = EntityUtils.toString(response.getEntity());
        } else if (response.getStatusLine().getStatusCode()
                / HTTP_STATUS_CODE_DIVISOR == HTTP_STATUS_CODE_API_ERROR) {
            responseBody = EntityUtils.toString(response.getEntity());

            throw new StockException(response.getStatusLine()
                    .getStatusCode(), responseBody);
        } else if (response.getStatusLine().getStatusCode()
                / HTTP_STATUS_CODE_DIVISOR
                    == HTTP_STATUS_CODE_SERVER_ERROR) {
            throw new StockException(response.getStatusLine()
                    .getStatusCode(), "API returned with Server Error");
        }

    } catch (StockException se) {
        throw se;
    } catch (Exception ex) {
        throw new StockException(-1, ex.getMessage());
    }

    return responseBody;
}