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

The following are Jave code examples for showing how to use consume() 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: Cognizant-Intelligent-Test-Scripter   File: QCRestHttpClient.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public JSONObject parseResponse(HttpResponse response) throws Exception {
    JSONObject jobj = new JSONObject();
    HttpEntity entity = response.getEntity();
    String resp;
    try {
        if (entity != null) {
            resp = EntityUtils.toString(entity);
            jobj.put("res", resp);
            jobj.put("status", response.getStatusLine().getStatusCode());
            if (LOGIN_KEY == null) {
                setLoginCookie(jobj, response);
            }
            EntityUtils.consume(entity);
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
    return jobj;
}
 
Example 2
Project: PowerApi   File: HttpUtil.java   View Source Code Vote up 6 votes
/**
 * 处理返回结果数据
 *
 * @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 3
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View Source Code Vote up 6 votes
/**
 * Returns information about a uncle by block number
 * @param blockNumber Block number
 * @param index Index
 * @return Block information
 */
public Block uncleByBlockNumberAndIndex(BigInteger blockNumber, BigInteger index) {

	HttpGet get = new HttpGet(PUBLIC_URL + "?module=proxy&action=eth_getUncleByBlockNumberAndIndex&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);

	Block current = new Block();

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

	return current;

}
 
Example 4
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View Source Code Vote up 6 votes
/**
 * Returns the latest Ether price in Wei
 * @return Latest Ether price in Wei
 */
public EtherPrice lastEtherPrice() {

	HttpGet get = new HttpGet(PUBLIC_URL + "?module=stats&action=ethprice&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);

	EtherPrice current = new EtherPrice();

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

	return current;

}
 
Example 5
Project: lams   File: HttpComponentsClientHttpResponse.java   View Source Code Vote up 6 votes
@Override
public void close() {
       // Release underlying connection back to the connection manager
       try {
           try {
               // Attempt to keep connection alive by consuming its remaining content
               EntityUtils.consume(this.httpResponse.getEntity());
           }
		finally {
               this.httpResponse.close();
           }
       }
       catch (IOException ex) {
		// Ignore exception on close...
       }
}
 
Example 6
Project: Sem-Update   File: VentanaPrincipal.java   View Source Code Vote up 6 votes
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 7
Project: tulingchat   File: HttpClientUtil.java   View Source Code Vote up 6 votes
/**
 * 通过httpClient get 下载文件
 *
 * @param url      网络文件全路径
 * @param savePath 保存文件全路径
 * @return 状态码 200表示成功
 */
public static int doDownload(String url, String savePath) {
	// 创建默认的HttpClient实例.
	CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
	HttpGet get = new HttpGet(url);
	CloseableHttpResponse closeableHttpResponse = null;
	try {
		closeableHttpResponse = closeableHttpClient.execute(get);
		HttpEntity entity = closeableHttpResponse.getEntity();
		if (entity != null) {
			InputStream in = entity.getContent();
			FileOutputStream out = new FileOutputStream(savePath);
			IOUtils.copy(in, out);
			EntityUtils.consume(entity);
			closeableHttpResponse.close();
		}
		int code = closeableHttpResponse.getStatusLine().getStatusCode();
		closeableHttpClient.close();
		return code;
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		closeSource(closeableHttpClient, closeableHttpResponse);
	}
	return 0;
}
 
Example 8
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 9
Project: CurseSync   File: CurseAPI.java   View Source Code Vote up 6 votes
@Nullable
private String getModSlug0(int id)
{
    try
    {
        log.debug("Getting mod slug from server...");
        URI uri = getURI(CURSEFORGE_URL, String.format(PROJECT_PATH, id), null);
        HttpGet request = new HttpGet(uri.toURL().toString());
        HttpContext context = new BasicHttpContext();
        HttpResponse response = http.execute(request, context);
        EntityUtils.consume(response.getEntity());
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        HttpHost currentHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI());
        Splitter splitter = Splitter.on('/').omitEmptyStrings();
        List<String> pathParts = splitter.splitToList(currentUrl);
        return pathParts.get(pathParts.size() - 1);
    }
    catch (Exception e)
    {
        log.error("Failed to perform request from CurseForge site.", e);
        return null;
    }
}
 
Example 10
Project: wherehowsX   File: HadoopJobHistoryNodeExtractor.java   View Source Code Vote up 5 votes
/**
 * Get the job conf from hadoop name node
 * @param hadoopJobId
 * @return the lineage info
 * @throws java.io.IOException
 */
public String getConfFromHadoop(String hadoopJobId)
  throws Exception {
  String url = this.serverURL + "/" + hadoopJobId + "/conf";
  logger.debug("get job conf from : {}", url);
  HttpUriRequest request = new HttpGet(url);
  HttpResponse response = httpClient.execute(request);
  HttpEntity entity = response.getEntity();
  String confResult = EntityUtils.toString(entity);
  EntityUtils.consume(entity);
  return confResult;
}
 
Example 11
Project: educational-plugin   File: EduAdaptiveStepicConnector.java   View Source Code Vote up 5 votes
@NotNull
private static StepicWrappers.ResultSubmissionWrapper getCheckResults(@NotNull CloseableHttpClient client,
                                                                      @NotNull StepicWrappers.ResultSubmissionWrapper wrapper,
                                                                      int attemptId,
                                                                      int userId) {
  try {
    while (wrapper.submissions.length == 1 && wrapper.submissions[0].status.equals("evaluation")) {
      TimeUnit.MILLISECONDS.sleep(500);
      final URI submissionURI = new URIBuilder(EduStepicNames.STEPIC_API_URL + EduStepicNames.SUBMISSIONS)
        .addParameter("attempt", String.valueOf(attemptId))
        .addParameter("order", "desc")
        .addParameter("user", String.valueOf(userId))
        .build();
      final HttpGet httpGet = new HttpGet(submissionURI);
      setTimeout(httpGet);
      final CloseableHttpResponse httpResponse = client.execute(httpGet);
      final HttpEntity entity = httpResponse.getEntity();
      final String entityString = EntityUtils.toString(entity);
      EntityUtils.consume(entity);
      wrapper = new Gson().fromJson(entityString, StepicWrappers.ResultSubmissionWrapper.class);
    }
  }
  catch (InterruptedException | URISyntaxException | IOException e) {
    LOG.warn(e.getMessage());
  }
  return wrapper;
}
 
Example 12
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View Source Code Vote up 5 votes
/**
 * Creates new message call transaction or a contract creation for signed transactions
 * @param txHex Raw hex encoded transaction to send
 * @return Error message or call result
 */
public String sendRawTransaction(String txHex) {

	HttpGet get = new HttpGet(PUBLIC_URL + "?module=proxy&action=eth_sendRawTransaction&hex=" + txHex + "&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("message"))
			return a.get(j).getValue().toString();
		else if(a.get(j).getName().toString().equals("result"))
			return a.get(j).getValue().toString();
	}

	return null;  // Null should not be expected when API is functional

}
 
Example 13
Project: fastcrawler   File: FetchResult.java   View Source Code Vote up 5 votes
public void discardContent(){
    try {
        if (entity != null) {
            EntityUtils.consume(entity);
        }
    }catch (Exception e){
        logger.warn("Unexpected error occurred while trying to discard content", e);
    }
}
 
Example 14
Project: cloud-ariba-partner-flow-extension-ext   File: PartnerFlowExtensionApiFacade.java   View Source Code Vote up 5 votes
/**
 * 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 15
Project: educational-plugin   File: EduStepicClient.java   View Source Code Vote up 5 votes
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 16
Project: lams   File: DecompressingHttpClient.java   View Source Code Vote up 5 votes
public <T> T execute(HttpHost target, HttpRequest request,
        ResponseHandler<? extends T> responseHandler, HttpContext context)
        throws IOException, ClientProtocolException {
    HttpResponse response = execute(target, request, context);
    try {
        return responseHandler.handleResponse(response);
    } finally {
        HttpEntity entity = response.getEntity();
        if (entity != null) EntityUtils.consume(entity);
    }
}
 
Example 17
Project: Equella   File: ItemApiEditTest.java   View Source Code Vote up 5 votes
@Test
public void testLockALockedItem() throws Exception
{
	final String token = getToken();
	ItemId itemId = createItem(token);

	// lock it
	HttpResponse response = null;
	try
	{
		response = lock(itemId, token, 201);
	}
	finally
	{
		if( response != null )
		{
			EntityUtils.consume(response.getEntity());
		}
	}

	// try to lock it again as a different user
	final String otherToken = requestToken(OAUTH_OTHER_CLIENT_ID);
	try
	{
		response = lock(itemId, otherToken, 409); // 409 == conflict
	}
	finally
	{
		if( response != null )
		{
			EntityUtils.consume(response.getEntity());
		}

		// unlock it
		unlock(itemId, token, 204);
	}
}
 
Example 18
Project: xvms   File: HttpTookit.java   View Source Code Vote up 4 votes
public String doPost(String url,List <NameValuePair> nvps,BasicCookieStore loginStatus) throws Exception{
	 
       CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(loginStatus).build();
       String webStr = "";
	try {
		//1Post请求
           HttpPost httpPost = new HttpPost(url);
           httpPost.setConfig(requestConfig);//设置超时配置
           
           	/*
           	 * nvps 内容
           	 * List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		     * //网页post参数 http://www.scnj.tv/appqy_api/api.php?api_key=AaPpQqYyCcOoMmLl&opt=getCategory
		     * nvps.add(new BasicNameValuePair("api_key", WEB_KEY));
		     * nvps.add(new BasicNameValuePair("opt", "login"));
		     * nvps.add(new BasicNameValuePair("uid", uid));
		     * nvps.add(new BasicNameValuePair("pass", password));
           	 * */
           	
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));//需加上UTF8 不然提交出去到网站会变成乱码 TODO 以后需要提取配置编码
			 
			CloseableHttpResponse response2;
			//2发送请求
			response2 = httpclient.execute(httpPost);
			System.out.println(response2.getStatusLine());
               //3处理响应结果
               if (response2.getStatusLine().getStatusCode() == 200) {
               	//4从输入流读取网页字符串内容
               	HttpEntity entity2 = response2.getEntity();
                   InputStream in = entity2.getContent();
                   webStr = readResponse(in);
                   //log.debug("网络请求接收到的返回数据"+webStr);
                   EntityUtils.consume(entity2);
               }
               // and ensure it is fully consumed
               response2.close();
	}catch(java.io.IOException e){
		e.getStackTrace();
		log.error("Web服务器端网络异常!info:"+e.getStackTrace().toString());
	}
	finally {
	//始终保持执行
          httpclient.close();
          
	}
	return webStr;
 
}
 
Example 19
Project: nest-spider   File: HttpClientUtil.java   View Source Code Vote up 4 votes
private String res(HttpRequestBase method) {
	HttpClientContext context = HttpClientContext.create();
	CloseableHttpResponse response = null;
	String content = RESPONSE_CONTENT;
	try {
		response = client.execute(method, context);//执行GET/POST请求
		HttpEntity entity = response.getEntity();//获取响应实体
		if(entity!=null) {
			Charset charset = ContentType.getOrDefault(entity).getCharset();
			content = EntityUtils.toString(entity, charset);
			EntityUtils.consume(entity);
		}
	} catch(ConnectTimeoutException cte) {
		LOG.error("请求连接超时,由于 " + cte.getLocalizedMessage());
		cte.printStackTrace();
	} catch(SocketTimeoutException ste) {
		LOG.error("请求通信超时,由于 " + ste.getLocalizedMessage());
		ste.printStackTrace();
	} catch(ClientProtocolException cpe) {
		LOG.error("协议错误(比如构造HttpGet对象时传入协议不对(将'http'写成'htp')or响应内容不符合),由于 " + cpe.getLocalizedMessage());
		cpe.printStackTrace();
	} catch(IOException ie) {
		LOG.error("实体转换异常或者网络异常, 由于 " + ie.getLocalizedMessage());
		ie.printStackTrace();
	} finally {
		try {
			if(response!=null) {
				response.close();
			}
			
		} catch(IOException e) {
			LOG.error("响应关闭异常, 由于 " + e.getLocalizedMessage());
		}
		
		if(method!=null) {
			method.releaseConnection();
		} 
		
	}
	
	return content;
}
 
Example 20
Project: universal-resolver   File: ClientUniResolver.java   View Source Code Vote up 3 votes
@Override
public DDO resolve(String identifier) throws ResolutionException {

	// prepare HTTP request

	String uriString = this.getResolverUri().toString();
	if (! uriString.endsWith("/")) uriString += "/";
	uriString += identifier;

	HttpGet httpGet = new HttpGet(URI.create(uriString));

	// retrieve DDO

	DDO ddo;

	try (CloseableHttpResponse httpResponse = (CloseableHttpResponse) this.getHttpClient().execute(httpGet)) {

		if (httpResponse.getStatusLine().getStatusCode() == 404) return null;
		if (httpResponse.getStatusLine().getStatusCode() > 200) throw new ResolutionException("Cannot retrieve DDO for " + identifier + " from " + uriString + ": " + httpResponse.getStatusLine());

		HttpEntity httpEntity = httpResponse.getEntity();

		ddo = DDO.fromString(EntityUtils.toString(httpEntity));
		EntityUtils.consume(httpEntity);
	} catch (IOException ex) {

		throw new ResolutionException("Cannot retrieve DDO for " + identifier + " from " + uriString + ": " + ex.getMessage(), ex);
	}

	if (log.isDebugEnabled()) log.debug("Retrieved DDO for " + identifier + " (" + uriString + "): " + ddo);

	// done

	return ddo;
}