Java Code Examples for org.apache.http.HttpEntity

The following are top voted examples for showing how to use org.apache.http.HttpEntity. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: yacy_grid_mcp   File: ClientConnection.java   View source code 13 votes vote down vote up
/**
 * get a redirect for an url: this method shall be called if it is expected that a url
 * is redirected to another url. This method then discovers the redirect.
 * @param urlstring
 * @param useAuthentication
 * @return the redirect url for the given urlstring
 * @throws IOException if the url is not redirected
 */
public static String getRedirect(String urlstring) throws IOException {
    HttpGet get = new HttpGet(urlstring);
    get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
    get.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    CloseableHttpClient httpClient = getClosableHttpClient();
    HttpResponse httpResponse = httpClient.execute(get);
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        if (httpResponse.getStatusLine().getStatusCode() == 301) {
            for (Header header: httpResponse.getAllHeaders()) {
                if (header.getName().equalsIgnoreCase("location")) {
                    EntityUtils.consumeQuietly(httpEntity);
                    return header.getValue();
                }
            }
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("redirect for  " + urlstring+ ": no location attribute found");
        } else {
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("no redirect for  " + urlstring+ " fail: " + httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase());
        }
    } else {
        throw new IOException("client connection to " + urlstring + " fail: no connection");
    }
}
 
Example 2
Project: CSipSimple   File: Sipgate.java   View source code 8 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public HttpRequestBase getRequest(SipProfile acc)  throws IOException {

    String requestURL = "https://samurai.sipgate.net/RPC2";
    HttpPost httpPost = new HttpPost(requestURL);
    // TODO : this is wrong ... we should use acc user/password instead of SIP ones, but we don't have it
    String userpassword = acc.username + ":" + acc.data;
    String encodedAuthorization = Base64.encodeBytes( userpassword.getBytes() );
    httpPost.addHeader("Authorization", "Basic " + encodedAuthorization);
    httpPost.addHeader("Content-Type", "text/xml");
    
    // prepare POST body
    String body = "<?xml version='1.0'?><methodCall><methodName>samurai.BalanceGet</methodName></methodCall>";

    // set POST body
    HttpEntity entity = new StringEntity(body);
    httpPost.setEntity(entity);
    return httpPost;
}
 
Example 3
Project: educational-plugin   File: EduAdaptiveStepicConnector.java   View source code 8 votes vote down vote up
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 4
Project: CSipSimple   File: Mobex.java   View source code 7 votes vote down vote up
@Override
public HttpRequestBase getRequest(SipProfile acc)  throws IOException {

    String requestURL = "http://200.152.124.172/billing/webservice/Server.php";
    
    HttpPost httpPost = new HttpPost(requestURL);
    httpPost.addHeader("SOAPAction", "\"mostra_creditos\"");
    httpPost.addHeader("Content-Type", "text/xml");

    // prepare POST body
    String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope " +
            "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" " +
            "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"" +
            "><SOAP-ENV:Body><mostra_creditos SOAP-ENC:root=\"1\">" +
            "<chave xsi:type=\"xsd:string\">" +
            acc.data +
            "</chave><username xsi:type=\"xsd:string\">" +
            acc.username.replaceAll("^12", "") +
            "</username></mostra_creditos></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    Log.d(THIS_FILE, "Sending request for user " + acc.username.replaceAll("^12", ""));
    // set POST body
    HttpEntity entity = new StringEntity(body);
    httpPost.setEntity(entity);
    return httpPost;
}
 
Example 5
Project: lams   File: EntityUtils.java   View source code 7 votes vote down vote up
/**
 * Obtains character set of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null
 *
 * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
 */
@Deprecated
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    String charset = null;
    if (entity.getContentType() != null) {
        HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}
 
Example 6
Project: tulingchat   File: HttpClientUtil.java   View source code 7 votes vote down vote up
/**
 * 通过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 7
Project: android-advanced-light   File: MainActivity.java   View source code 6 votes vote down vote up
private void useHttpClientPost(String url) {
    HttpPost mHttpPost = new HttpPost(url);
    mHttpPost.addHeader("Connection", "Keep-Alive");
    try {
        HttpClient mHttpClient = createHttpClient();
        List<NameValuePair> postParams = new ArrayList<>();
        //要传递的参数
        postParams.add(new BasicNameValuePair("ip", "59.108.54.37"));
        mHttpPost.setEntity(new UrlEncodedFormEntity(postParams));
        HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
        HttpEntity mHttpEntity = mHttpResponse.getEntity();
        int code = mHttpResponse.getStatusLine().getStatusCode();
        if (null != mHttpEntity) {
            InputStream mInputStream = mHttpEntity.getContent();
            String respose = converStreamToString(mInputStream);
            Log.d(TAG, "请求状态码:" + code + "\n请求结果:\n" + respose);
            mInputStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: integration-test-helper   File: AomHttpClient.java   View source code 6 votes vote down vote up
/**
 * Sets the app to active state
 *
 * @param customerName
 *        the name of the customer
 * @param appName
 *        the name of the app
 * @return request object to check status codes and return values
 */
public Response deployApp( String customerName, String appName )
{
	HttpPut request = new HttpPut( this.yambasBase + "customers/" + customerName + "/apps/" + appName );
	setAuthorizationHeader( request );
	request.addHeader( "ContentType", "application/json" );
	request.addHeader( "x-apiomat-system", this.system.toString( ) );
	try
	{
		final HttpEntity requestEntity = new StringEntity(
			"{\"applicationStatus\":{\"" + this.system + "\":\"ACTIVE\"}, \"applicationName\":\"" +
				appName + "\"}",
			ContentType.APPLICATION_JSON );
		request.setEntity( requestEntity );

		final HttpResponse response = this.client.execute( request );
		return new Response( response );
	}
	catch ( final IOException e )
	{
		e.printStackTrace( );
	}
	return null;
}
 
Example 9
Project: allure-java   File: AllureHttpClientRequest.java   View source code 6 votes vote down vote up
@Override
public void process(final HttpRequest request,
                    final HttpContext context) throws HttpException, IOException {
    final HttpRequestAttachment.Builder builder = create("Request", request.getRequestLine().getUri())
            .withMethod(request.getRequestLine().getMethod());

    Stream.of(request.getAllHeaders())
            .forEach(header -> builder.withHeader(header.getName(), header.getValue()));

    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();

        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        entity.writeTo(os);

        final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
        builder.withBody(body);
    }

    final HttpRequestAttachment requestAttachment = builder.build();
    processor.addAttachment(requestAttachment, renderer);
}
 
Example 10
Project: restheart-java-client   File: RestHeartClientApi.java   View source code 6 votes vote down vote up
private RestHeartClientResponse extractFromResponse(final CloseableHttpResponse httpResponse) {
    RestHeartClientResponse response = null;
    JsonObject responseObj = null;
    if (httpResponse != null) {
        StatusLine statusLine = httpResponse.getStatusLine();
        Header[] allHeaders = httpResponse.getAllHeaders();
        HttpEntity resEntity = httpResponse.getEntity();
        if (resEntity != null) {
            try {
                String responseStr = IOUtils.toString(resEntity.getContent(), "UTF-8");
                if (responseStr != null && !responseStr.isEmpty()) {
                    JsonParser parser = new JsonParser();
                    responseObj = parser.parse(responseStr).getAsJsonObject();
                }
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, "Was unable to extract response body", e);
            }
        }

        response = new RestHeartClientResponse(statusLine, allHeaders, responseObj);
    }
    return response;
}
 
Example 11
Project: jspider   File: Request.java   View source code 6 votes vote down vote up
public Request(String id,
               String method,
               String url,
               ResponseType responseType,
               Map<String, String> headers,
               Map<String, String> parameters,
               HttpEntity entity,
               Map<String, String> extras) {
    this.id = StringUtils.isNotBlank(id) ? id : SpiderStrUtils.getUUID();
    this.method = StringUtils.isNotBlank(method) ? method : Request.METHOD_GET;
    this.url = url;
    this.responseType = responseType != null ? responseType : ResponseType.TEXT;
    this.headers = headers;
    this.parameters = parameters;
    this.entity = entity;
    this.extras = extras;
}
 
Example 12
Project: pyroclast-java   File: ReadAggregateGroupParser.java   View source code 6 votes vote down vote up
@Override
public ReadAggregateGroupResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            HttpEntity entity = response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(entity.getContent(), writer, "UTF-8");
            String json = writer.toString();

            return mapper.readValue(json, ReadAggregateGroupResult.class);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
Example 13
Project: pyroclast-java   File: SubscribeToTopicParser.java   View source code 6 votes vote down vote up
@Override
public PyroclastConsumer parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            HttpEntity entity = response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(entity.getContent(), writer, "UTF-8");
            String json = writer.toString();

            SubscribeToTopicResult result = mapper.readValue(json, SubscribeToTopicResult.class);

            if (result.getSuccess()) {
                return new PyroclastConsumer(topicId, readApiKey, format, endpoint, subscriptionName);
            } else {
                throw new UnknownAPIException(result.getFailureReason());
            }

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
Example 14
Project: integration-test-helper   File: AomHttpClient.java   View source code 6 votes vote down vote up
/**
 * Updates a modules config for the given app
 *
 * @param customerName
 *        the name of the customer
 * @param appName
 *        the name of the app
 * @param moduleName
 *        the name of the module to update config for
 * @param key
 *        config key
 * @param value
 *        value of the config
 * @return request object to check status codes and return values
 */
public Response updateConfig( String customerName, String appName, String moduleName, String key,
	String value )
{
	final HttpPut request = new HttpPut( this.yambasBase + "customers/" + customerName + "/apps/" + appName );
	setAuthorizationHeader( request );
	request.addHeader( "ContentType", "application/json" );
	request.addHeader( "x-apiomat-system", this.system.toString( ) );
	try
	{
		final HttpEntity requestEntity = new StringEntity(
			"{\"configuration\":" + "	{\"" + this.system.toString( ).toLowerCase( ) + "Config\": {\"" +
				moduleName + "\":{\"" + key + "\":\"" + value + "\"}}}, \"applicationName\":\"" + appName + "\"}",
			ContentType.APPLICATION_JSON );
		request.setEntity( requestEntity );

		final HttpResponse response = this.client.execute( request );
		return new Response( response );
	}
	catch ( final IOException e )
	{
		e.printStackTrace( );
	}
	return null;
}
 
Example 15
Project: act-platform   File: FactSearchManager.java   View source code 6 votes vote down vote up
private void createIndex() {
  Response response;

  try (InputStream payload = FactSearchManager.class.getClassLoader().getResourceAsStream(MAPPINGS_JSON)) {
    // Need to use low-level client here because the Index API is not yet supported by the high-level client.
    HttpEntity body = new InputStreamEntity(payload, ContentType.APPLICATION_JSON);
    response = clientFactory.getLowLevelClient().performRequest("PUT", INDEX_NAME, Collections.emptyMap(), body);
  } catch (IOException ex) {
    throw logAndExit(ex, "Could not perform request to create index.");
  }

  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    String msg = String.format("Could not create index '%s'.", INDEX_NAME);
    LOGGER.error(msg);
    throw new IllegalStateException(msg);
  }

  LOGGER.info("Successfully created index '%s'.", INDEX_NAME);
}
 
Example 16
Project: jkes   File: HttpClient.java   View source code 6 votes vote down vote up
public Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity) throws IOException {
    HttpRequestBase httpRequestBase = buildRequest(method, host, endpoint, params, entity);

    try (CloseableHttpResponse response = httpclient.execute(httpRequestBase)) {
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();

        Response resp = Response.builder()
                .statusCode(statusLine.getStatusCode())
                .content(responseEntity == null ? null : EntityUtils.toString(responseEntity))
                .build();

        EntityUtils.consume(responseEntity);

        return resp;
    }
}
 
Example 17
Project: neo-java   File: GeoIPUtil.java   View source code 6 votes vote down vote up
/**
 * returns the location of a host.
 *
 * @param canonicalHostName
 *            the host name to use.
 * @return the location, as JSON.
 */
public static JSONObject getLocation(final String canonicalHostName) {
	try {
		final String urlStr = "https://freegeoip.net/json/" + canonicalHostName;
		final HttpGet get = new HttpGet(urlStr);
		final RequestConfig requestConfig = RequestConfig.custom().build();
		get.setConfig(requestConfig);
		final CloseableHttpClient client = HttpClients.createDefault();
		final CloseableHttpResponse response = client.execute(get);
		final HttpEntity entity = response.getEntity();
		final String str = EntityUtils.toString(entity);
		final JSONObject outputJson = new JSONObject(str);
		LOG.info("outputJson:{}", outputJson);
		return outputJson;
	} catch (final IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 18
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View source code 6 votes vote down vote up
/**
 * Returns code at a given address
 * @param address Address
 * @return Code at given address
 */
public String getCode(String address) {

	HttpGet get = new HttpGet(PUBLIC_URL + "?module=proxy&action=eth_getCode&address=" + address + "&tag=latest" + "&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 a.get(j).getValue().toString();

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

}
 
Example 19
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View source code 6 votes vote down vote up
public static void loadBug18993(){
	try{
		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8011),
				new UsernamePasswordCredentials("admin", "admin"));
		String document ="<foo>a space b</foo>";
		String  perm = "perm:rest-writer=read&perm:rest-writer=insert&perm:rest-writer=update&perm:rest-writer=execute";
		HttpPut put = new HttpPut("http://"+host+":8011/v1/documents?uri=/a%20b&"+perm);
		put.addHeader("Content-type", "application/xml");
		put.setEntity(new StringEntity(document)); 	
		HttpResponse response = client.execute(put);
		HttpEntity respEntity = response.getEntity();
		if(respEntity != null){
			String content =  EntityUtils.toString(respEntity);
			System.out.println(content);
		}
	}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}

}
 
Example 20
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View source code 6 votes vote down vote up
/**
 * Get Token account balance by known Token name (Supported Token names: DGD, MKR, FirstBlood, HackerGold, ICONOMI, Pluton, REP, SNGLS)
 * @param tokenName Token name
 * @param address Address
 * @return Token account balance
 */
public BigInteger getTokenAccountBalance(String tokenName, String address) {

	HttpGet get = new HttpGet(PUBLIC_URL + "?module=account&action=tokenbalance&tokenname=" + tokenName + "&address=" + address + "&tag=latest" + "&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 21
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View source code 6 votes vote down vote up
/**
 * Get Ether balance for a single address in Wei
 * @param address Address
 * @return Balance
 */
public Balance etherBalance(String address) {

	HttpGet get = new HttpGet(PUBLIC_URL + "?module=account&action=balance&address=" + address + "&tag=latest&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().equals("result")) { // Equals compares names
			return new Balance(address, new BigInteger(a.get(j).getValue().toString()));
		}
	}

	return null;

}
 
Example 22
Project: InComb   File: TxtContentReader.java   View source code 6 votes vote down vote up
/**
 * Returns the content read form content-source.
 * @return read {@link Content}
 */
@Override
public Content[] read(final FetchHistory lastFetch) {

	final CloseableHttpClient httpClient = HttpClients.createDefault();
	final HttpGet httpget = new HttpGet(contentSource.getUrl());
	final HttpContext context = new BasicHttpContext();

	CloseableHttpResponse response = null;
	String stringRead = null;

	try {
		try {
			LOGGER.info("Loading uri: " + httpget.getURI());
			response = httpClient.execute(httpget, context);
			final HttpEntity entity = response.getEntity();

			if (entity != null) {
				stringRead = IOUtils.toString(entity.getContent());
				LOGGER.info("Read {} bytes from: {}", stringRead.getBytes().length, httpget.getURI());
			}

		} finally {
			CloseUtil.close(response);
			CloseUtil.close(httpClient);
		}

	} catch (final Exception e) {
		LOGGER.warn("Error occurred while reading text document: " + contentSource.getUrl());
	}

	return new Content[] { createContentObject(stringRead) };
}
 
Example 23
Project: netto_rpc   File: NginxServiceProvider.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, RouteConfig> getRouterMap() {
	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(Constants.DEFAULT_TIMEOUT)
			.setConnectionRequestTimeout(Constants.DEFAULT_TIMEOUT).setSocketTimeout(Constants.DEFAULT_TIMEOUT)
			.build();
	HttpClient httpClient = this.httpPool.getResource();
	try {
		StringBuilder sb = new StringBuilder(50);
		sb.append(this.getServerDesc().getRegistry())
				.append(this.getServerDesc().getRegistry().endsWith("/") ? "" : "/")
				.append(this.getServerDesc().getServerApp()).append("/routers");
		HttpGet get = new HttpGet(sb.toString());
		get.setConfig(requestConfig);
		// 创建参数队列
		HttpResponse response = httpClient.execute(get);
		HttpEntity entity = response.getEntity();
		String body = EntityUtils.toString(entity, "UTF-8");
		ObjectMapper mapper = JsonMapperUtil.getJsonMapper();
		return mapper.readValue(body, Map.class);
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw new RuntimeException(e);
	} finally {
		this.httpPool.release(httpClient);
	}
}
 
Example 24
Project: lams   File: URLEncodedUtils.java   View source code 6 votes vote down vote up
/**
 * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an
 * {@link HttpEntity}. The encoding is taken from the entity's
 * Content-Encoding header.
 * <p>
 * This is typically used while parsing an HTTP POST.
 *
 * @param entity
 *            The entity to parse
 * @throws IOException
 *             If there was an exception getting the entity's data.
 */
public static List <NameValuePair> parse (
        final HttpEntity entity) throws IOException {
    ContentType contentType = ContentType.get(entity);
    if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) {
        String content = EntityUtils.toString(entity, Consts.ASCII);
        if (content != null && content.length() > 0) {
            Charset charset = contentType.getCharset();
            if (charset == null) {
                charset = HTTP.DEF_CONTENT_CHARSET;
            }
            return parse(content, charset);
        }
    }
    return Collections.emptyList();
}
 
Example 25
Project: Cryptocurrency-Java-Wrappers   File: Etherscan.java   View source code 6 votes vote down vote up
/**
 * Returns the number of transactions in a block from a block matching the given block number
 * @param blockNumber Block number
 * @return Number of transactions
 */
public BigInteger blockTransactionCountByNumber(BigInteger blockNumber) {

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

	for(int j = 0; j < a.size(); j++)
		if(a.get(j).getName().toString().equals("result"))
			return new BigInteger(a.get(j).getValue().toString().substring(2), 16); // Hex to dec

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

}
 
Example 26
Project: Zmap_test   File: RegisterByUsername.java   View source code 6 votes vote down vote up
private void sendRequestWithHttpClient(){
    final String username_text = username.getText().toString().trim();
    final String password_text = password.getText().toString().trim();
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpClient httpCient = new DefaultHttpClient();  //创建HttpClient对象
            HttpGet httpGet = new HttpGet(url+"/?action=register&username="+username_text+"&password="+password_text);
            try {
                HttpResponse httpResponse = httpCient.execute(httpGet);//第三步:执行请求,获取服务器发还的相应对象
                if((httpResponse.getEntity())!=null){
                    HttpEntity entity =httpResponse.getEntity();
                    String response = EntityUtils.toString(entity,"utf-8");//将entity当中的数据转换为字符串

                    Message message = new Message();//在子线程中将Message对象发出去
                    message.what = SHOW_RESPONSE;
                    message.obj =response;
                    handler.sendMessage(message);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }).start();
}
 
Example 27
Project: bitstd   File: HttpUtilManager.java   View source code 6 votes vote down vote up
public String requestHttpGet(String url_prex, String type) throws HttpException, IOException {
	String url = url_prex + type;
	HttpRequestBase method = this.httpGetMethod(url, "");
	method.setConfig(requestConfig);
	long start = System.currentTimeMillis();
	HttpResponse response = client.execute(method);
	long end = System.currentTimeMillis();
	Logger.getGlobal().log(Level.INFO, String.valueOf(end - start));
	HttpEntity entity = response.getEntity();
	if (entity == null) {
		return "";
	}
	InputStream is = null;
	String responseData = "";
	try {
		is = entity.getContent();
		responseData = IOUtils.toString(is, "UTF-8");
	} finally {
		if (is != null) {
			is.close();
		}
	}
	return responseData;
}
 
Example 28
Project: Zmap_test   File: LoginAccount.java   View source code 6 votes vote down vote up
private void sendRequestWithHttpClient_history(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpClient httpCient = new DefaultHttpClient();  //创建HttpClient对象
            HttpGet httpGet = new HttpGet(url+"/history.php?action=getSearchHistory&id="+resp_user.getUser_id()
                    +"&username="+resp_user.getUsername());
            try {
                HttpResponse httpResponse = httpCient.execute(httpGet);//第三步:执行请求,获取服务器发还的相应对象
                if((httpResponse.getEntity())!=null){
                    HttpEntity entity =httpResponse.getEntity();
                    String response = EntityUtils.toString(entity,"utf-8");//将entity当中的数据转换为字符串
                    resp_user.setSearchHistory(response);
                    resp_user.updateAll("User_id > ?","0");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }).start();
}
 
Example 29
Project: java-pilosa   File: PilosaClient.java   View source code 6 votes vote down vote up
private QueryResponse queryPath(QueryRequest request) {
    String path = String.format("/index/%s/query", request.getIndex().getName());
    Internal.QueryRequest qr = request.toProtobuf();
    ByteArrayEntity body = new ByteArrayEntity(qr.toByteArray());
    try {
        CloseableHttpResponse response = clientExecute("POST", path, body, protobufHeaders, "Error while posting query",
                ReturnClientResponse.RAW_RESPONSE);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            try (InputStream src = entity.getContent()) {
                QueryResponse queryResponse = QueryResponse.fromProtobuf(src);
                if (!queryResponse.isSuccess()) {
                    throw new PilosaException(queryResponse.getErrorMessage());
                }
                return queryResponse;
            }
        }
        throw new PilosaException("Server returned empty response");
    } catch (IOException ex) {
        throw new PilosaException("Error while reading response", ex);
    }
}
 
Example 30
Project: TITAN   File: Stresstest.java   View source code 6 votes vote down vote up
/**
 * 获取执行结果
 * 
 * @author gaoxianglong
 * 
 * @param httpResponse
 * 
 * @param entity
 * 
 * @exception Exception
 * 
 * @return OutParamBean
 */
public default OutParamBO getResult(CloseableHttpResponse httpResponse, HttpEntity entity) {
	OutParamBO outParamBO = new OutParamBO();
	int httpCode = 200;
	if (httpCode == httpResponse.getStatusLine().getStatusCode()) {
		outParamBO.setErrorCode(httpCode);
		try {
			JSONObject obj = JSONObject.parseObject(EntityUtils.toString(entity, CHAR_SET));
			Object errorCode = obj.get("errorCode");
			Object data = obj.get("data");
			if (null != errorCode) {
				outParamBO.setErrorCode(Integer.parseInt(errorCode.toString()));
			}
			if (null != data) {
				outParamBO.setData(data.toString());
			}
		} catch (Exception e) {
			log.debug("返回的并非是JSON");
		}
	}
	return outParamBO;
}
 
Example 31
Project: omero-ms-queue   File: JsonResponseHandlers.java   View source code 5 votes vote down vote up
private static HttpEntity fetchEntity(HttpResponse response)
        throws ClientProtocolException {
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        throw new ClientProtocolException("Response contains no entity.");
    }
    return entity;
}
 
Example 32
Project: keycloak-protocol-cas   File: LogoutHelper.java   View source code 5 votes vote down vote up
public static HttpEntity buildSingleLogoutRequest(String serviceTicket) {
    String id = IDGenerator.create("ID_");
    XMLGregorianCalendar issueInstant;
    try {
        issueInstant = XMLTimeUtil.getIssueInstant();
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
    String document = TEMPLATE.replace("$ID", id).replace("$ISSUE_INSTANT", issueInstant.toString())
            .replace("$SESSION_IDENTIFIER", serviceTicket);
    return new StringEntity(document, ContentType.APPLICATION_XML.withCharset(StandardCharsets.UTF_8));
}
 
Example 33
Project: elasticsearch-client   File: ESRest.java   View source code 5 votes vote down vote up
public <T> T put(String resource, String body ,Class<T> responseClass, boolean assertSuccess) throws IOException {
	final HttpEntity entity = new NStringEntity(body, ContentType.APPLICATION_JSON);
	final Response response = client.performRequest("PUT", resource, Collections.<String, String>emptyMap(),
			entity);
	if (assertSuccess) {
		assertSuccess(response);
	}
	return mapper.readValue(IOUtils.toString(response.getEntity().getContent(), "UTF-8"), responseClass);
}
 
Example 34
Project: http-agent   File: AgentServlet.java   View source code 5 votes vote down vote up
/** Copy response body data (the entity) from the proxy to the servlet client. */
protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletResponse servletResponse) throws IOException {
    HttpEntity entity = proxyResponse.getEntity();
    if (entity != null) {
        OutputStream servletOutputStream = servletResponse.getOutputStream();
        entity.writeTo(servletOutputStream);
    }
}
 
Example 35
Project: GitHub   File: HttpClientStack.java   View source code 5 votes vote down vote up
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
        Request<?> request) throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
 
Example 36
Project: swaggy-jenkins   File: DeleteRequest.java   View source code 5 votes vote down vote up
public DeleteRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
  super(Method.DELETE, url, errorListener);
  mListener = listener;
  this.entity = entity;
  this.contentType = contentType;
  this.apiHeaders = apiHeaders;
}
 
Example 37
Project: jiracli   File: HttpClient.java   View source code 5 votes vote down vote up
private static Charset getEncoding(HttpEntity entity) {
    if (entity.getContentEncoding() != null) {
        String value = entity.getContentEncoding().getValue();
        if (value != null) {
            try {
                return Charset.forName(value);
            } catch (RuntimeException e) {
                // use the default charset!
                LOGGER.debug("Unsupported charset: {}", value, e);
            }
        }
    }
    return StandardCharsets.UTF_8;
}
 
Example 38
Project: jkes   File: EsRestClient.java   View source code 5 votes vote down vote up
public Response performRequest(String method, String endpoint, Map<String, String> params,
                               JSONObject entity, Header... headers) {
    try {
        HttpEntity payload = new NStringEntity(JsonUtils.convertToString(entity), ContentType.APPLICATION_JSON);
        return restClient.performRequest(method, endpoint, params, payload, HttpAsyncResponseConsumerFactory.DEFAULT, headers);
    } catch (IOException e) {
        throw new RequestException(
                String.format("request exception. method: %s, endpoint: %s, params: %s, entity: %s",
                        method, endpoint, params, entity),
                e);
    }
}
 
Example 39
Project: karate   File: RequestLoggingInterceptor.java   View source code 5 votes vote down vote up
@Override
public void process(org.apache.http.HttpRequest request, HttpContext httpContext) throws HttpException, IOException {
    HttpRequest actual = new HttpRequest();
    int id = counter.incrementAndGet();
    String uri = (String) httpContext.getAttribute(ApacheHttpClient.URI_CONTEXT_KEY);
    String method = request.getRequestLine().getMethod();
    actual.setUri(uri);        
    actual.setMethod(method);
    StringBuilder sb = new StringBuilder();
    sb.append('\n').append(id).append(" > ").append(method).append(' ').append(uri).append('\n');
    LoggingUtils.logHeaders(sb, id, '>', request, actual);
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (LoggingUtils.isPrintable(entity)) {
            LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity); // todo optimize, preserve if stream
            if (context.logger.isDebugEnabled()) {
                String buffer = FileUtils.toString(wrapper.getContent());
                sb.append(buffer).append('\n');
            }
            actual.setBody(wrapper.getBytes());
            entityRequest.setEntity(wrapper);
        }
    }
    context.setPrevRequest(actual);
    if (context.logger.isDebugEnabled()) {
        context.logger.debug(sb.toString());
    }
}
 
Example 40
Project: Snow-Globe   File: CallUtility.java   View source code 5 votes vote down vote up
/**
 * This gets the response body out of the entity object.
 *
 * @param entity the entity contained in the response.
 * @return A string value of the response body.
 */
static String getResponseBody(HttpEntity entity) {
    StringBuilder sb = new StringBuilder();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()), 65728);
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return sb.toString();
}