本文整理汇总了Java中org.apache.http.util.EntityUtils.toString方法的典型用法代码示例。如果您正苦于以下问题:Java EntityUtils.toString方法的具体用法?Java EntityUtils.toString怎么用?Java EntityUtils.toString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.util.EntityUtils
的用法示例。
在下文中一共展示了EntityUtils.toString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: execute0
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
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;
}
示例2: getResponseContent
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
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;
}
示例3: getErc20TokenTotalSupply
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
/**
* 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
}
示例4: transactionByBlockNumberAndIndex
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
/**
* 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;
}
示例5: postRecommendationReaction
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
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;
}
}
示例6: getAsString
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
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());
}
示例7: matches
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
@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;
}
}
示例8: GetDate
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
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;
}
}
示例9: get
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
/**
* 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;
}
示例10: getContent
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
/**
* <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;
}
示例11: testOAuthWithTokenLogin
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
@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
}
示例12: testGetURL
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
@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");
}
示例13: main
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
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);
}
示例14: executeAndGet
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
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;
}
示例15: testSpecificConsumerRetrieval
import org.apache.http.util.EntityUtils; //导入方法依赖的package包/类
@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();
}