org.apache.http.client.methods.HttpGet#setURI()源码实例Demo

下面列出了org.apache.http.client.methods.HttpGet#setURI() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: nexus-public   文件: NexusITSupport.java
/**
 * 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();
    }
  }
}
 
源代码2 项目: nexus-public   文件: NexusITSupport.java
/**
 * 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();
    }
  }
}
 
源代码3 项目: container   文件: WineryConnector.java
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;
    }
}
 
源代码4 项目: gsn   文件: RemoteRestAPIWrapper.java
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);
			}
		}
	}
}
 
源代码5 项目: kylin-on-parquet-v2   文件: RestClient.java
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);
    }
}
 
源代码6 项目: charging_pile_cloud   文件: HttpClientUtil.java
/**
 * 封装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;
}
 
源代码7 项目: flash-waimai   文件: HttpClients.java
/**
 * 封装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;
}
 
源代码8 项目: flash-waimai   文件: HttpClients.java
/**
 * 封装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;
}
 
源代码9 项目: javabase   文件: GetClient.java
/**
 *
 * @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();
    }

}
 
源代码10 项目: dal   文件: WebUtil.java
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;
    }
}
 
源代码11 项目: scheduling   文件: GetNodeThreadDumpCommand.java
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;
}
 
源代码12 项目: kylin   文件: RestClient.java
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);
    }
}
 
源代码13 项目: program-ab   文件: NetworkUtils.java
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();
}
 
private HttpGet createHttpGetRequest() {
	final HttpGet result = new HttpGet();
	result.setURI(getUri());
	appendHeaders(result);
	return result;
}
 
源代码15 项目: container   文件: WineryConnector.java
/**
 * 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);
    }
}
 
源代码16 项目: TurkcellUpdater_android_sdk   文件: RestRequest.java
private HttpGet createHttpGetRequest() {
	final HttpGet result = new HttpGet();
	result.setURI(getUri());
	appendHeaders(result);
	return result;
}
 
@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);
}
 
@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);
}
 
@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);
}
 
@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);
}