Java Code Examples for org.apache.http.client.methods.HttpGet#setURI()

The following examples show how to use org.apache.http.client.methods.HttpGet#setURI() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Preform a get request
 *
 * @param baseUrl               (nexusUrl in most tests)
 * @param path                  to the resource
 * @param headers               {@link Header}s
 * @param useDefaultCredentials use {@link NexusITSupport#clientBuilder(URL, boolean)} for using credentials
 * @return the response object
 */
protected Response get(final URL baseUrl,
                       final String path,
                       final Header[] headers,
                       final boolean useDefaultCredentials) throws Exception
{
  HttpGet request = new HttpGet();
  request.setURI(UriBuilder.fromUri(baseUrl.toURI()).path(path).build());
  request.setHeaders(headers);

  try (CloseableHttpClient client = clientBuilder(nexusUrl, useDefaultCredentials).build()) {

    try (CloseableHttpResponse response = client.execute(request)) {
      ResponseBuilder responseBuilder = Response.status(response.getStatusLine().getStatusCode());
      Arrays.stream(response.getAllHeaders()).forEach(h -> responseBuilder.header(h.getName(), h.getValue()));

      HttpEntity entity = response.getEntity();
      if (entity != null) {
        responseBuilder.entity(new ByteArrayInputStream(IOUtils.toByteArray(entity.getContent())));
      }
      return responseBuilder.build();
    }
  }
}
 
Example 2
/**
 * Preform a get request
 *
 * @param baseUrl               (nexusUrl in most tests)
 * @param path                  to the resource
 * @param headers               {@link Header}s
 * @param useDefaultCredentials use {@link NexusITSupport#clientBuilder(URL, boolean)} for using credentials
 * @return the response object
 */
protected Response get(final URL baseUrl,
                       final String path,
                       final Header[] headers,
                       final boolean useDefaultCredentials) throws Exception
{
  HttpGet request = new HttpGet();
  request.setURI(UriBuilder.fromUri(baseUrl.toURI()).path(path).build());
  request.setHeaders(headers);

  try (CloseableHttpClient client = clientBuilder(nexusUrl, useDefaultCredentials).build()) {

    try (CloseableHttpResponse response = client.execute(request)) {
      ResponseBuilder responseBuilder = Response.status(response.getStatusLine().getStatusCode());
      Arrays.stream(response.getAllHeaders()).forEach(h -> responseBuilder.header(h.getName(), h.getValue()));

      HttpEntity entity = response.getEntity();
      if (entity != null) {
        responseBuilder.entity(new ByteArrayInputStream(IOUtils.toByteArray(entity.getContent())));
      }
      return responseBuilder.build();
    }
  }
}
 
Example 3
Source Project: container   File: WineryConnector.java    License: Apache License 2.0 6 votes vote down vote up
public boolean isWineryRepositoryAvailable() {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final URI serviceTemplatesUri = new URI(this.wineryPath + "servicetemplates");
        LOG.debug("Checking if winery is available at " + serviceTemplatesUri.toString());

        final HttpGet get = new HttpGet();
        get.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
        get.setURI(serviceTemplatesUri);
        final CloseableHttpResponse resp = httpClient.execute(get);
        resp.close();

        return resp.getStatusLine().getStatusCode() < 400;
    } catch (URISyntaxException | IOException e) {
        LOG.error("Exception while checking for availability of Container Repository: ", e);
        return false;
    }
}
 
Example 4
public void run() {
	getData = new HttpGet();
	while (isActive()) {
		String uri = wsURL + "/api/sensors/" + vsName + "/data?from=" + ISODateTimeFormat.dateTime().print(lastReceivedTimestamp);
		try {
			getData.setURI(new URI(uri));
			String content = doRequest(getData);
			for (StreamElement se : StreamElement.fromJSON(content)){
				manualDataInsertion(se);
			}
			Thread.sleep(samplingPeriodInMsc);
		}
		catch (Exception e) {
			logger.warn("Something went wrong when querying the REST API at " + uri + " trying again in 1 minute...");
			try {
				if (isActive()) {
					Thread.sleep(60000);
				}
			} catch (Exception err) {
				logger.debug(err.getMessage(), err);
			}
		}
	}
}
 
Example 5
Source Project: kylin-on-parquet-v2   File: RestClient.java    License: Apache License 2.0 5 votes vote down vote up
public HashMap getCube(String cubeName) throws Exception {
    String url = baseUrl + CUBES + cubeName;
    HttpGet get = newGet(url);
    HttpResponse response = null;
    try {
        get.setURI(new URI(url));
        response = client.execute(get);
        return dealResponse(response);
    } finally {
        cleanup(get, response);
    }
}
 
Example 6
Source Project: charging_pile_cloud   File: HttpClientUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 封装HTTP GET方法
 *
 * @param
 * @param
 * @return
 */
public static String get(String url, Map<String, String> paramMap)
        throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet();
    List<NameValuePair> formparams = setHttpParams(paramMap);
    String param = URLEncodedUtils.format(formparams, "UTF-8");
    httpGet.setURI(URI.create(url + "?" + param));
    HttpResponse response = httpClient.execute(httpGet);
    String httpEntityContent = getHttpEntityContent(response);
    httpGet.abort();
    return httpEntityContent;
}
 
Example 7
Source Project: flash-waimai   File: HttpClients.java    License: MIT License 5 votes vote down vote up
/**
 * 封装HTTP GET方法
 *
 * @param
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String get(String url) throws ClientProtocolException, IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpGet httpGet = new HttpGet();
	httpGet.setURI(URI.create(url));
	HttpResponse response = httpClient.execute(httpGet);
	String httpEntityContent = getHttpEntityContent(response);
	httpGet.abort();
	return httpEntityContent;
}
 
Example 8
Source Project: flash-waimai   File: HttpClients.java    License: MIT License 5 votes vote down vote up
/**
 * 封装HTTP GET方法
 *
 * @param
 * @param
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String get(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpGet httpGet = new HttpGet();
	List<NameValuePair> formparams = setHttpParams(paramMap);
	String param = URLEncodedUtils.format(formparams, "UTF-8");
	httpGet.setURI(URI.create(url + "?" + param));
	HttpResponse response = httpClient.execute(httpGet);
	String httpEntityContent = getHttpEntityContent(response);
	httpGet.abort();
	return httpEntityContent;
}
 
Example 9
Source Project: javabase   File: GetClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @throws IOException
 */
//http://jinnianshilongnian.iteye.com/blog/2089792
public void standard() throws IOException {
  //  CloseableHttpClient httpclient = new DefaultHttpClient(getHttpParams());
    HttpResponse response = null;
    HttpEntity entity = null;
    try {
        HttpGet get = new HttpGet();
        String url = "http://www.baidu.com/";
        get.setURI(new URI(url));
        //执行
        response = getHttpClient().execute(get);
        log.info("status:" + response.getStatusLine());
        entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        log.info(result);
        //处理响应
    } catch (Exception e) {
        log.error("" + e.getLocalizedMessage());
        //处理异常
    } finally {
        if (response != null) {
            EntityUtils.consume(entity); //会自动释放连接
        }
        //关闭
       // httpclient.getConnectionManager().shutdown();
    }

}
 
Example 10
Source Project: dal   File: WebUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Response getAllInOneResponse(String keyname, String environment) throws Exception {
    Response res = null;
    if (keyname == null || keyname.isEmpty())
        return res;
    if (SERVICE_RUL == null || SERVICE_RUL.isEmpty())
        return res;
    if (APP_ID == null || APP_ID.isEmpty())
        return res;

    try {
        URIBuilder builder = new URIBuilder(SERVICE_RUL).addParameter("ids", keyname).addParameter("appid", APP_ID);
        if (environment != null && !environment.isEmpty())
            builder.addParameter("envt", environment);

        URI uri = builder.build();
        HttpClient sslClient = initWeakSSLClient();
        if (sslClient != null) {
            HttpGet httpGet = new HttpGet();
            httpGet.setURI(uri);
            HttpResponse response = sslClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String content = EntityUtils.toString(entity);
            res = JSON.parseObject(content, Response.class);
        }

        return res;
    } catch (Throwable e) {
        throw e;
    }
}
 
Example 11
private HttpGet buildGetNodeThreadDumpRequest(ApplicationContext context) {
    HttpGet request = new HttpGet(context.getResourceUrl("node/threaddump"));
    try {
        URI requestUri = new URIBuilder(request.getURI()).addParameter("nodeurl", this.nodeUrl).build();
        request.setURI(requestUri);
    } catch (URISyntaxException e) {
        writeLine(context, "An error occurred while retrieving node thread dump: %s", e.getMessage());
    }
    return request;
}
 
Example 12
Source Project: kylin   File: RestClient.java    License: Apache License 2.0 5 votes vote down vote up
public HashMap getCube(String cubeName) throws Exception {
    String url = baseUrl + CUBES + cubeName;
    HttpGet get = newGet(url);
    HttpResponse response = null;
    try {
        get.setURI(new URI(url));
        response = client.execute(get);
        return dealResponse(response);
    } finally {
        cleanup(get, response);
    }
}
 
Example 13
public static String responseContent(String url) throws Exception {
	HttpClient client = new DefaultHttpClient();
	HttpGet request = new HttpGet();
	request.setURI(new URI(url));
	InputStream is = client.execute(request).getEntity().getContent();
	BufferedReader inb = new BufferedReader(new InputStreamReader(is));
	StringBuilder sb = new StringBuilder("");
	String line;
	String NL = System.getProperty("line.separator");
	while ((line = inb.readLine()) != null) {
		sb.append(line).append(NL);
	}
	inb.close();
	return sb.toString();
}
 
Example 14
private HttpGet createHttpGetRequest() {
	final HttpGet result = new HttpGet();
	result.setURI(getUri());
	appendHeaders(result);
	return result;
}
 
Example 15
Source Project: container   File: WineryConnector.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Performs management feature enrichment for the CSAR represented by the given file.
 *
 * @param file the file containing the CSAR for the management feature enrichment
 */
public void performManagementFeatureEnrichment(final File file) {
    if (!isWineryRepositoryAvailable()) {
        LOG.error("Management feature enrichment enabled, but Container Repository is not available!");
        return;
    }
    LOG.debug("Container Repository is available. Uploading file {} to repo...", file.getName());
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        // upload CSAR to enable enrichment in Winery
        final String location = uploadCSARToWinery(file, false);

        if (Objects.isNull(location)) {
            LOG.error("Upload return location equal to null!");
            return;
        }

        LOG.debug("Stored CSAR at location: {}", location.toString());

        // get all available features for the given CSAR
        final HttpGet get = new HttpGet();
        get.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
        get.setURI(new URI(location + FEATURE_ENRICHMENT_SUFFIX));
        CloseableHttpResponse resp = httpClient.execute(get);
        final String jsonResponse = EntityUtils.toString(resp.getEntity());
        resp.close();

        LOG.debug("Container Repository returned the following features:", jsonResponse);

        // apply the found features to the CSAR
        final HttpPut put = new HttpPut();
        put.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        put.setURI(new URI(location + FEATURE_ENRICHMENT_SUFFIX));
        final StringEntity stringEntity = new StringEntity(jsonResponse);
        put.setEntity(stringEntity);
        resp = httpClient.execute(put);
        resp.close();

        LOG.debug("Feature enrichment returned status line: {}", resp.getStatusLine());

        // retrieve updated CSAR from winery
        final URL url = new URL(location + "/?csar");
        Files.copy(url.openStream(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        LOG.debug("Updated CSAR file in the Container with enriched topology.");
    } catch (final Exception e) {
        LOG.error("{} while performing management feature enrichment: {}", e.getClass().getSimpleName(), e.getMessage(), e);
    }
}
 
Example 16
private HttpGet createHttpGetRequest() {
	final HttpGet result = new HttpGet();
	result.setURI(getUri());
	appendHeaders(result);
	return result;
}
 
Example 17
@Override
protected String doInBackground(String... params) {

    StringBuffer sb=new StringBuffer("");
    link = "http://satyajiit.xyz/quiz/getPts.php?user="+username+"&pass="+password;

    try {


        URL url = new URL(link);
        Log.d("CSE", "back");
        HttpClient client = new DefaultHttpClient();
        Log.d("CSE", "back2");
        HttpGet request = new HttpGet();
        Log.d("CSE", "back3");
        request.setURI(new URI(link));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new
                InputStreamReader(response.getEntity().getContent()));


        String line = "";

        while ((line = in.readLine()) != null) {
            sb.append(line);
            break;
        }

        in.close();




    }
    catch(Exception e){
        sb=new StringBuffer("sads");
        Log.d("CSE", String.valueOf(e));
    }





    return String.valueOf(sb);
}
 
Example 18
@Override
protected String doInBackground(String... params) {

    StringBuffer sb = new StringBuffer("");
    link = "http://satyajiit.xyz/quiz/chkUpd.php?ver=" + ver;

    try {


        URL url = new URL(link);

        HttpClient client = new DefaultHttpClient();

        HttpGet request = new HttpGet();

        request.setURI(new URI(link));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new
                InputStreamReader(response.getEntity().getContent()));


        String line = "";

        while ((line = in.readLine()) != null) {
            sb.append(line);
            break;
        }

        in.close();




    } catch (Exception e) {
        sb = new StringBuffer("sads");
        Log.d("CSE", String.valueOf(e));
    }


    return String.valueOf(sb);
}
 
Example 19
@Override
protected String doInBackground(String... params) {

    StringBuffer sb=new StringBuffer("");
    link = "http://satyajiit.xyz/quiz/getPts.php?user="+username+"&pass="+password;

    try {

        URL url = new URL(link);
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(link));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new
                InputStreamReader(response.getEntity().getContent()));


        String line = "";

        while ((line = in.readLine()) != null) {
            sb.append(line);
            break;
        }

        in.close();




    }
    catch(Exception e){
        sb=new StringBuffer("sads");

    }





    return String.valueOf(sb);
}
 
Example 20
@Override
protected String doInBackground(String... params) {

    StringBuffer sb2=new StringBuffer("");

    link2 = "http://satyajiit.xyz/quiz/newUser.php?user="+username+"&pass="+password+"&cor="+cor;

    try {

        URL url2 = new URL(link2);
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(link2));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new
                InputStreamReader(response.getEntity().getContent()));


        String line2 = "";

        while ((line2 = in.readLine())!=null) {
            sb2.append(line2);
            break;
        }

        in.close();



    }
    catch(Exception e){
        sb2=new StringBuffer("sads");

    }





    return String.valueOf(sb2);
}