Example usage for org.springframework.http HttpEntity HttpEntity

List of usage examples for org.springframework.http HttpEntity HttpEntity

Introduction

In this page you can find the example usage for org.springframework.http HttpEntity HttpEntity.

Prototype

public HttpEntity(MultiValueMap<String, String> headers) 

Source Link

Document

Create a new HttpEntity with the given headers and no body.

Usage

From source file:nl.flotsam.calendar.core.CalendarClient.java

public String getCalendarAsType(String key, String contentType) {
    String address = UriBuilder.fromUri(baseURI).path("calendars").build().toASCIIString() + "/{key}";
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("key", key);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", contentType);
    HttpEntity<?> request = new HttpEntity(headers);
    HttpEntity<String> response = template.exchange(address, HttpMethod.GET, request, String.class, params);
    return response.getBody();
}

From source file:de.muenchen.eaidemo.AbstractIntegrationTest.java

/**
 * @param requestMappingUrl should be exactly the same as defined in your
 * RequestMapping value attribute (including the parameters in {})
 * RequestMapping(value = yourRestUrl)/* w  ww  .  j  ava2s .  c o m*/
 * @param serviceListReturnTypeClass should be the the generic type of the
 * list the service returns, eg: List<serviceListReturnTypeClass>
 * @param parametersInOrderOfAppearance should be the parameters of the
 * requestMappingUrl ({}) in order of appearance
 * @return the result of the service, or null on error
 */
protected <T> List<T> getList(final String requestMappingUrl, final Class<T> serviceListReturnTypeClass,
        final Object... parametersInOrderOfAppearance) {
    final ObjectMapper mapper = new ObjectMapper();
    final TestRestTemplate restTemplate = new TestRestTemplate();
    final HttpEntity<String> requestEntity = new HttpEntity<String>(new HttpHeaders());
    try {
        // Retrieve list
        final ResponseEntity<List> entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl,
                HttpMethod.GET, requestEntity, List.class, parametersInOrderOfAppearance);
        final List<Map<String, String>> entries = entity.getBody();
        final List<T> returnList = new ArrayList<T>();
        for (final Map<String, String> entry : entries) {
            // Fill return list with converted objects
            returnList.add(mapper.convertValue(entry, serviceListReturnTypeClass));
        }
        return returnList;
    } catch (final Exception ex) {
        // Handle exceptions
    }
    return null;
}

From source file:com.bailen.radioOnline.recursos.REJA.java

public Cancion[] getRatings(String apiKey) throws IOException {
    HttpHeaders header = new HttpHeaders();
    header.set("Authorization", apiKey);
    HttpEntity entity = new HttpEntity(header);
    String lista = new String();
    HttpEntity<String> response;
    response = new RestTemplate().exchange("http://ceatic.ujaen.es:8075/radioapi/v2/ratings", HttpMethod.GET,
            entity, String.class, lista);

    String canc = response.getBody();
    StringTokenizer st = new StringTokenizer(canc, "[", true);
    st.nextToken();/* w  ww. j av a 2  s .  c o  m*/
    if (!st.hasMoreTokens()) {
        return null;
    }
    st.nextToken();
    canc = "[" + st.nextToken();

    try {

        ObjectMapper a = new ObjectMapper();
        ItemPuntu[] listilla = a.readValue(canc, ItemPuntu[].class);
        Vector<Integer> ids = new Vector<>();
        Vector<Cancion> punt = new Vector<>();
        //como jamendo solo devuelve 10 canciones llamamos las veces necesarias
        for (int i = 0; i < (listilla.length / 10) + 1; ++i) {
            ids.clear();
            //aunque le mandemos mas ids de la cuenta solo devolvera las 10 primeras canciones y 
            //de esta forma controlamos el desborde
            for (int j = i * 10; j < listilla.length; ++j) {
                ids.add(listilla[j].getId());
            }
            Cancion[] listilla1 = jamendo.canciones(ids);
            for (int k = 0; k < listilla1.length; ++k) {
                punt.add(listilla1[k]);
            }
        }

        for (int i = 0; i < punt.size(); ++i) {
            punt.get(i).setRating(listilla[i].getRating());
            punt.get(i).setFav(listilla[i].getFav());
        }

        return punt.toArray(new Cancion[punt.size()]);

    } catch (Exception e) {
        //return null;
        throw new IOException("no se han recibido canciones");
    }

}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchExperiments.java

/**
 * Method, where all experiments are read from server.
 * All heavy lifting is made here.//from   ww  w .  j  av  a2  s.com
 *
 * @param params not used (omitted) here
 * @return list of fetched experiments
 */
@Override
protected List<Experiment> doInBackground(Void... params) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_EXPERIMENTS;

    setState(RUNNING, R.string.working_ws_experiments);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    HttpEntity<Object> entity = new HttpEntity<Object>(requestHeaders);

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    try {

        //obtain all public records if qualifier is all
        if (Values.SERVICE_QUALIFIER_ALL.equals(qualifier)) {
            String countUrl = url + "count";
            ResponseEntity<RecordCount> count = restTemplate.exchange(countUrl, HttpMethod.GET, entity,
                    RecordCount.class);

            url += "public/" + count.getBody().getPublicRecords();
        } else
            url += qualifier;

        // Make the network request
        Log.d(TAG, url);
        ResponseEntity<ExperimentList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                ExperimentList.class);
        ExperimentList body = response.getBody();

        if (body != null) {
            return body.getExperiments();
        }

    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return Collections.emptyList();
}

From source file:net.orpiske.tcs.client.services.TagCloudServiceClient.java

@Override
public DomainList requestDomainList() {
    ResponseEntity<DomainList> responseEntity = restTemplate.exchange(endPoint.getDomainListLocation(),
            HttpMethod.GET, new HttpEntity<Object>(getHeaders()), DomainList.class);

    return responseEntity.getBody();
}

From source file:org.cloudfoundry.caldecott.client.HttpTunnel.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void close() {
    if (logger.isDebugEnabled()) {
        logger.debug("Deleting tunnel " + this.tunnelInfo.get("path"));
    }//ww  w .  j ava 2 s  . c  o m
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Auth-Token", auth);
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    try {
        restOperations.exchange(url + this.tunnelInfo.get("path"), HttpMethod.DELETE, requestEntity, null);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().value() == 404) {
            if (logger.isDebugEnabled()) {
                logger.debug("Tunnel not found [" + e.getStatusCode() + "] " + e.getStatusText());
            }
        } else {
            logger.warn("Error while deleting tunnel [" + e.getStatusCode() + "] " + e.getStatusText());
        }
    }
}

From source file:com.wisemapping.test.rest.RestAccountITCase.java

private ResponseEntity<RestUser> findUserByEmail(HttpHeaders requestHeaders, RestTemplate templateRest,
        final String email) {
    HttpEntity<RestUser> findUserEntity = new HttpEntity<RestUser>(requestHeaders);

    // Add extension only to avoid the fact that the last part is extracted ...
    final String url = BASE_REST_URL + "/admin/users/email/{email}.json";
    return templateRest.exchange(url, HttpMethod.GET, findUserEntity, RestUser.class, email);
}

From source file:com.cloud.baremetal.networkservice.Force10BaremetalSwitchBackend.java

@Override
public void prepareVlan(BaremetalVlanStruct struct) {
    String link = buildLink(struct.getSwitchIp(),
            String.format("/api/running/ftos/interface/vlan/%s", struct.getVlan()));
    HttpHeaders headers = createBasicAuthenticationHeader(struct);
    HttpEntity<String> request = new HttpEntity<>(headers);
    ResponseEntity rsp = rest.exchange(link, HttpMethod.GET, request, String.class);
    logger.debug(String.format("http get: %s", link));

    if (rsp.getStatusCode() == HttpStatus.NOT_FOUND) {
        PortInfo port = new PortInfo(struct);
        XmlObject xml = new XmlObject("vlan")
                .putElement("vlan-id", new XmlObject("vlan-id").setText(String.valueOf(struct.getVlan())))
                .putElement("untagged",
                        new XmlObject("untagged").putElement(port.interfaceType,
                                new XmlObject(port.interfaceType).putElement("name",
                                        new XmlObject("name").setText(port.port))))
                .putElement("shutdown", new XmlObject("shutdown").setText("false"));
        request = new HttpEntity<>(xml.dump(), headers);
        link = buildLink(struct.getSwitchIp(), String.format("/api/running/ftos/interface/"));
        logger.debug(String.format("http get: %s, body: %s", link, request));
        rsp = rest.exchange(link, HttpMethod.POST, request, String.class);
        if (!successHttpStatusCode.contains(rsp.getStatusCode())) {
            throw new CloudRuntimeException(String.format(
                    "unable to create vlan[%s] on force10 switch[ip:%s]. HTTP status code:%s, body dump:%s",
                    struct.getVlan(), struct.getSwitchIp(), rsp.getStatusCode(), rsp.getBody()));
        } else {/* w  ww  .j a va 2  s . c  o m*/
            logger.debug(String.format(
                    "successfully programmed vlan[%s] on Force10[ip:%s, port:%s]. http response[status code:%s, body:%s]",
                    struct.getVlan(), struct.getSwitchIp(), struct.getPort(), rsp.getStatusCode(),
                    rsp.getBody()));
        }
    } else if (successHttpStatusCode.contains(rsp.getStatusCode())) {
        PortInfo port = new PortInfo(struct);
        XmlObject xml = XmlObjectParser.parseFromString((String) rsp.getBody());
        List<XmlObject> ports = xml.getAsList("untagged.tengigabitethernet");
        ports.addAll(xml.<XmlObject>getAsList("untagged.gigabitethernet"));
        ports.addAll(xml.<XmlObject>getAsList("untagged.fortyGigE"));
        for (XmlObject pxml : ports) {
            XmlObject name = pxml.get("name");
            if (port.port.equals(name.getText())) {
                logger.debug(String.format("port[%s] has joined in vlan[%s], no need to program again",
                        struct.getPort(), struct.getVlan()));
                return;
            }
        }

        xml.removeElement("mtu");
        xml.setText(null);
        XmlObject tag = xml.get("untagged");
        if (tag == null) {
            tag = new XmlObject("untagged");
            xml.putElement("untagged", tag);
        }

        tag.putElement(port.interfaceType,
                new XmlObject(port.interfaceType).putElement("name", new XmlObject("name").setText(port.port)));
        request = new HttpEntity<>(xml.dump(), headers);
        link = buildLink(struct.getSwitchIp(),
                String.format("/api/running/ftos/interface/vlan/%s", struct.getVlan()));
        logger.debug(String.format("http get: %s, body: %s", link, request));
        rsp = rest.exchange(link, HttpMethod.PUT, request, String.class);
        if (!successHttpStatusCode.contains(rsp.getStatusCode())) {
            throw new CloudRuntimeException(String.format(
                    "failed to program vlan[%s] for port[%s] on force10[ip:%s]. http status:%s, body dump:%s",
                    struct.getVlan(), struct.getPort(), struct.getSwitchIp(), rsp.getStatusCode(),
                    rsp.getBody()));
        } else {
            logger.debug(String.format(
                    "successfully join port[%s] into vlan[%s] on Force10[ip:%s]. http response[status code:%s, body:%s]",
                    struct.getPort(), struct.getVlan(), struct.getSwitchIp(), rsp.getStatusCode(),
                    rsp.getBody()));
        }
    } else {
        throw new CloudRuntimeException(
                String.format("force10[ip:%s] returns unexpected error[%s] when http getting %s, body dump:%s",
                        struct.getSwitchIp(), rsp.getStatusCode(), link, rsp.getBody()));
    }
}

From source file:org.cloudfoundry.caldecott.client.TunnelHelper.java

public static Map<String, String> getTunnelServiceInfo(CloudFoundryClient client, String serviceName) {
    String urlToUse = getTunnelUri(client) + "/services/" + serviceName;
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Auth-Token", getTunnelAuth(client));
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    HttpEntity<String> response = restTemplate.exchange(urlToUse, HttpMethod.GET, requestEntity, String.class);
    String json = response.getBody().trim();
    Map<String, String> svcInfo = new HashMap<String, String>();
    try {//from w w w.j a  v a 2 s . c  o m
        svcInfo = convertJsonToMap(json);
    } catch (IOException e) {
        return new HashMap<String, String>();
    }
    if (svcInfo.containsKey("url")) {
        String svcUrl = svcInfo.get("url");
        try {
            URI uri = new URI(svcUrl);
            String[] userInfo;
            if (uri.getUserInfo().contains(":")) {
                userInfo = uri.getUserInfo().split(":");
            } else {
                userInfo = new String[2];
                userInfo[0] = uri.getUserInfo();
                userInfo[1] = "";
            }
            svcInfo.put("user", userInfo[0]);
            svcInfo.put("username", userInfo[0]);
            svcInfo.put("password", userInfo[1]);
            svcInfo.put("host", uri.getHost());
            svcInfo.put("hostname", uri.getHost());
            svcInfo.put("port", "" + uri.getPort());
            svcInfo.put("path", (uri.getPath().startsWith("/") ? uri.getPath().substring(1) : uri.getPath()));
            svcInfo.put("vhost", svcInfo.get("path"));
        } catch (URISyntaxException e) {
        }
    }
    return svcInfo;
}