当前位置: 首页>>代码示例>>Java>>正文


Java EntityUtils.toString方法代码示例

本文整理汇总了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;
}
 
开发者ID:wxz1211,项目名称:dooo,代码行数:17,代码来源:OpenClient.java

示例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;
        }
 
开发者ID:AschPlatform,项目名称:asch-java,代码行数:23,代码来源:REST.java

示例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

}
 
开发者ID:Jaewan-Yun,项目名称:Cryptocurrency-Java-Wrappers,代码行数:29,代码来源:Etherscan.java

示例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;

}
 
开发者ID:Jaewan-Yun,项目名称:Cryptocurrency-Java-Wrappers,代码行数:31,代码来源:Etherscan.java

示例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;
  }
}
 
开发者ID:medvector,项目名称:educational-plugin,代码行数:28,代码来源:EduAdaptiveStepicConnector.java

示例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());
}
 
开发者ID:tiberiusteng,项目名称:financisto1-holo,代码行数:9,代码来源:HttpClientWrapper.java

示例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;
    }
}
 
开发者ID:PawelAdamski,项目名称:HttpClientMock,代码行数:14,代码来源:BodyMatcher.java

示例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;
    }
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:11,代码来源:LEYUApplication.java

示例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;
}
 
开发者ID:pjbank,项目名称:pjbank-java-sdk,代码行数:40,代码来源:Credenciamento.java

示例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;
}
 
开发者ID:apache,项目名称:sling-org-apache-sling-testing-clients,代码行数:20,代码来源:SlingHttpResponse.java

示例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
}
 
开发者ID:equella,项目名称:Equella,代码行数:16,代码来源:OAuthTest.java

示例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");
}
 
开发者ID:pawankumbhare4213,项目名称:TinyURL,代码行数:12,代码来源:TinyURLServiceTest.java

示例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);
}
 
开发者ID:strictnerd,项目名称:LearningSummary,代码行数:13,代码来源:HttpRequestUtil.java

示例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;
}
 
开发者ID:yaogdu,项目名称:datax,代码行数:28,代码来源:HttpClientUtil.java

示例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();
}
 
开发者ID:wso2,项目名称:message-broker,代码行数:48,代码来源:ConsumersRestApiTest.java


注:本文中的org.apache.http.util.EntityUtils.toString方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。