當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。