List of usage examples for org.springframework.http HttpHeaders setAccept
public void setAccept(List<MediaType> acceptableMediaTypes)
From source file:com.formkiq.web.AbstractIntegrationTest.java
/** * Send Rest API with object.//w ww. j a va2s . co m * @param method HttpMethod * @param url String * @param obj Object * @param clazz Class<T> * @param <T> Type of class * @param mediaType {@link MediaType} * @return ResponseEntity<String> */ protected <T> ResponseEntity<T> exchangeRest(final HttpMethod method, final String url, final Object obj, final Class<T> clazz, final MediaType mediaType) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(mediaType); headers.setAccept(Arrays.asList(ACCEPT_HEADER_V1_JSON)); HttpEntity<Object> entity = new HttpEntity<>(obj, headers); ResponseEntity<T> out = getTemplate().exchange(url, method, entity, clazz); return out; }
From source file:com.formkiq.web.AbstractIntegrationTest.java
/** * Sends Rest API./*from w ww .j av a2 s. c o m*/ * @param <T> Type of Response * @param method HttpMethod * @param url String * @param responseType {@link Class} * @param acceptableMediaTypes {@link List} * @return ResponseEntity<String> */ protected <T> ResponseEntity<T> exchangeRest(final HttpMethod method, final String url, final Class<T> responseType, final List<MediaType> acceptableMediaTypes) { HttpHeaders headers = new HttpHeaders(); headers.add("User-Agent", "Dummy User Agent"); headers.setAccept(acceptableMediaTypes); HttpEntity<String> e = new HttpEntity<>("parameters", headers); ResponseEntity<T> entity = getTemplate().exchange(url, method, e, responseType); return entity; }
From source file:com.jaspersoft.android.sdk.client.JsRestClient.java
/** * Downloads specified report attachment, once a report has been generated, and keeps it in memory as a byte array. * * @param uuid Universally Unique Identifier. As a side effect of storing the report output in the user session, * the UUID in the URI is visible only to the currently logged in user. * @param name One of the file names specified in the report xml. If the file parameter is not specified, * the service returns the report descriptor. * @return Attachment file as byte array stored in memory. * @throws RestClientException thrown by RestTemplate whenever it encounters client-side HTTP errors *///from ww w. j a v a2 s .c o m public byte[] getReportAttachment(String uuid, String name) throws RestClientException { String fullUri = restServicesUrl + REST_REPORT_URI + "/{uuid}?file={name}"; HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(singletonList(MediaType.APPLICATION_OCTET_STREAM)); ResponseEntity<byte[]> entity = restTemplate.exchange(fullUri, HttpMethod.GET, new HttpEntity<byte[]>(requestHeaders), byte[].class, uuid, name); return entity.getBody(); }
From source file:com.jaspersoft.android.sdk.client.JsRestClient.java
/** * Runs the report and generates the specified output. The response contains report descriptor * with the ID of the saved output for downloading later with a GET request. * * @param resourceDescriptor resource descriptor of this report * @param format The format of the report output. Possible values: PDF, HTML, XLS, RTF, CSV, * XML, JRPRINT. The Default is PDF. * @return ReportDescriptor//from ww w .j a va 2 s . c o m * @throws RestClientException thrown by RestTemplate whenever it encounters client-side HTTP errors */ public ReportDescriptor getReportDescriptor(ResourceDescriptor resourceDescriptor, String format) throws RestClientException { String fullUri = restServicesUrl + REST_REPORT_URI + resourceDescriptor.getUriString() + "?IMAGES_URI=./&RUN_OUTPUT_FORMAT={format}"; HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(singletonList(MediaType.TEXT_XML)); HttpEntity<ResourceDescriptor> requestEntity = new HttpEntity<ResourceDescriptor>(resourceDescriptor, requestHeaders); ResponseEntity<ReportDescriptor> entity = restTemplate.exchange(fullUri, HttpMethod.PUT, requestEntity, ReportDescriptor.class, format); return entity.getBody(); }
From source file:cz.cvut.via.androidrestskeleton.SkeletonActivity.java
/** Called with the activity is first created. */ @Override//from w w w . j av a 2s . co m public void onCreate(Bundle savedInstanceState) { // DISABLE policy not allowing network connections from main application thread // these calls normally HAVE to be done from worker threads/asynchronous threads/services .. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); super.onCreate(savedInstanceState); // Inflate our UI from its XML layout description. setContentView(R.layout.skeleton_activity); requestView = (CheckedTextView) findViewById(R.id.checkedTextRequest); responseView = (CheckedTextView) findViewById(R.id.checkedTextResponse); // Hook up button presses to the appropriate event handler. ((Button) findViewById(R.id.create)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { PostalAddress address = new PostalAddress(); address.setCity("new city"); address.setCountry("new country"); address.setStreet("new street"); address.setZipCode("zipcode"); // request HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(new MediaType("application", "json")); HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders); // endpoint final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/"; new AsyncPOST<PostalAddress>(requestEntity) { protected void onPostExecute(Response<String> result) { requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n" + request.getBody().toJSONString()); responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n" + result.getResponseEntity().getHeaders().toString()); lastCreatedLocation = result.getResponseEntity().getHeaders().getLocation().getPath(); }; }.execute(url); } }); // Hook up button presses to the appropriate event handler. ((Button) findViewById(R.id.list)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { RestTemplate restTemplate = new RestTemplate(); // request HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json"))); HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestHeaders); // endpoint final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/"; new AsyncGET<PostalAddress[]>(requestEntity, PostalAddress[].class) { protected void onPostExecute(Response<PostalAddress[]> result) { requestView.setText(url + "\n\n" + request.getHeaders()); if (result.getEx() != null) { showError(result.getEx()); } else { StringBuilder text = new StringBuilder(); for (PostalAddress address : result.getResponseEntity().getBody()) { text.append(address.toJSONString() + "\n\n"); } //+ requestEntity.getBody().toJSONString()); responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n" + result.getResponseEntity().getHeaders().toString() + "\n\n" + text); } }; }.execute(url); } }); ((Button) findViewById(R.id.update)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { PostalAddress address = new PostalAddress(); address.setCity("updated city"); address.setCountry("new country"); address.setStreet("new street"); address.setZipCode("zipcode"); // request HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(new MediaType("application", "json")); HttpEntity<PostalAddress> requestEntity = new HttpEntity<PostalAddress>(address, requestHeaders); // endpoint final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation; new AsyncPUT<PostalAddress>(requestEntity) { protected void onPostExecute(Response<Object> result) { requestView.setText(url + "\n\n" + request.getHeaders().toString() + "\n\n" + request.getBody().toJSONString()); if (result.getEx() != null) { showError(result.getEx()); } else { responseView.setText("PUT method in Spring does not support return values.."); } }; }.execute(url); } }); ((Button) findViewById(R.id.delete)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // endpoint final String url = YOUR_SERVER_URL_NO_END_SLASH + lastCreatedLocation; // get reponse new AsyncDELETE() { protected void onPostExecute(Response<Object> result) { requestView.setText(url); if (result.getEx() != null) { showError(result.getEx()); } else { responseView.setText("PUT method in Spring does not support return values.."); } }; }.execute(url); } }); ((Button) findViewById(R.id.query)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { HashMap<String, String> query = new HashMap<String, String>(); query.put("setFilter", "street == streetParam"); query.put("declareParameters", "String streetParam"); query.put("setOrdering", "street desc"); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("streetParam", "new street"); RESTQuery q = new RESTQuery(); q.setQuery(query); q.setParameters(parameters); // request HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(new MediaType("application", "json")); HttpEntity<RESTQuery> requestEntity = new HttpEntity<RESTQuery>(q, requestHeaders); // endpoint final String url = YOUR_SERVER_URL_NO_END_SLASH + "/address/q"; // get reponse new AsyncPOST_QUERY<RESTQuery, PostalAddress[]>(requestEntity, PostalAddress[].class) { @Override protected void onPostExecute(Response<PostalAddress[]> result) { requestView.setText(url + "\n\n" + request.getHeaders()); if (result.getEx() != null) { showError(result.getEx()); } else { StringBuilder text = new StringBuilder(); for (PostalAddress address : result.getResponseEntity().getBody()) { text.append(address.toJSONString() + "\n\n"); } responseView.setText(result.getResponseEntity().getStatusCode() + "\n\n" + result.getResponseEntity().getHeaders().toString() + "\n\n" + text); } } }.execute(url); } }); }
From source file:com.muk.services.api.impl.PayPalPaymentService.java
private String getTokenHeader() { final Cache cache = cacheManager.getCache(ServiceConstants.CacheNames.paymentApiTokenCache); final String token = "paypal"; ValueWrapper valueWrapper = cache.get(token); String cachedHeader = StringUtils.EMPTY; if (valueWrapper == null || valueWrapper.get() == null) { try {/*from w ww .j a va 2s . c om*/ final String value = securityCfgService.getPayPalClientId() + ":" + keystoreService.getPBEKey(securityCfgService.getPayPalClientId()); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.add(HttpHeaders.AUTHORIZATION, "Basic " + nonceService.encode(value.getBytes(StandardCharsets.UTF_8))); final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>(); body.add("grant_type", "client_credentials"); final HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>( body, headers); final ResponseEntity<JsonNode> response = restTemplate.postForEntity( securityCfgService.getPayPalUri() + "/oauth2/token", request, JsonNode.class); cache.put(token, response.getBody().get("access_token").asText()); valueWrapper = cache.get(token); cachedHeader = (String) valueWrapper.get(); } catch (final IOException ioEx) { LOG.error("Failed read keystore", ioEx); cachedHeader = StringUtils.EMPTY; } catch (final GeneralSecurityException secEx) { LOG.error("Failed to get key", secEx); cachedHeader = StringUtils.EMPTY; } } else { cachedHeader = (String) valueWrapper.get(); } return "Bearer " + cachedHeader; }
From source file:com.muk.services.api.impl.PayPalPaymentService.java
private ResponseEntity<JsonNode> send(String path, JsonNode payload) { final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); headers.add(HttpHeaders.AUTHORIZATION, getTokenHeader()); return restTemplate.postForEntity(securityCfgService.getPayPalUri() + path, new HttpEntity<JsonNode>(payload, headers), JsonNode.class); }
From source file:com.muk.services.api.impl.StripePaymentService.java
private ResponseEntity<JsonNode> send(String path, JsonNode payload) { final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.add(HttpHeaders.AUTHORIZATION, getTokenHeader()); final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>(); final Iterator<Entry<String, JsonNode>> nodes = payload.fields(); while (nodes.hasNext()) { final Map.Entry<String, JsonNode> entry = nodes.next(); if (entry.getValue().isObject()) { final String key = entry.getKey(); final Iterator<Entry<String, JsonNode>> metadataNodes = entry.getValue().fields(); while (metadataNodes.hasNext()) { final Map.Entry<String, JsonNode> element = metadataNodes.next(); body.add(key + "[\"" + element.getKey() + "\"]", element.getValue().asText()); }/*from w ww .j av a 2 s . co m*/ } else { body.add(entry.getKey(), entry.getValue().asText()); } } return restTemplate.postForEntity(securityCfgService.getStripeUri() + path, new HttpEntity<MultiValueMap<String, String>>(body, headers), JsonNode.class); }
From source file:com.muk.services.security.DefaultUaaLoginService.java
@SuppressWarnings("unchecked") @Override//from w w w . j av a2 s . co m public Map<String, Object> loginForClient(String username, String password, String clientId, UriComponents inUrlComponents) { final Map<String, Object> responsePayload = new HashMap<String, Object>(); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer()); // login for csrf final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("login").build(); ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.GET, null, headers, String.class); final List<String> cookies = new ArrayList<String>(); cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE)); final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", username); formData.add("password", password); formData.add(CSRF, getCsrf(cookies)); headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies)); headers.add(HttpHeaders.REFERER, loginUri.toUriString()); // login.do response = exchangeForType(uriBuilder.cloneBuilder().pathSegment("login.do").build().toUriString(), HttpMethod.POST, formData, headers, String.class); if (response.getStatusCode() != HttpStatus.FOUND || response.getHeaders().getFirst(HttpHeaders.LOCATION).contains("login")) { responsePayload.put("error", "bad credentials"); return responsePayload; } removeCookie(cookies, "X-Uaa-Csrf"); cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE)); removeExpiredCookies(cookies); headers.remove(HttpHeaders.REFERER); headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies)); // authorize final ResponseEntity<JsonNode> authResponse = exchangeForType( uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize") .queryParam("response_type", "code").queryParam("client_id", clientId) .queryParam("redirect_uri", inUrlComponents.toUriString()).build().toUriString(), HttpMethod.GET, null, headers, JsonNode.class); if (authResponse.getStatusCode() == HttpStatus.OK) { removeCookie(cookies, "X-Uaa-Csrf"); cookies.addAll(authResponse.getHeaders().get(HttpHeaders.SET_COOKIE)); // return approval data final List<HttpCookie> parsedCookies = new ArrayList<HttpCookie>(); for (final String cookie : cookies) { parsedCookies.add(HttpCookie.parse(cookie).get(0)); } responsePayload.put(HttpHeaders.SET_COOKIE, new ArrayList<String>()); for (final HttpCookie parsedCookie : parsedCookies) { if (!parsedCookie.getName().startsWith("Saved-Account")) { parsedCookie.setPath(inUrlComponents.getPath()); ((List<String>) responsePayload.get(HttpHeaders.SET_COOKIE)) .add(httpCookieToString(parsedCookie)); } } responsePayload.put("json", authResponse.getBody()); } else { // get auth_code from Location Header responsePayload.put("code", authResponse.getHeaders().getLocation().getQuery().split("=")[1]); } return responsePayload; }
From source file:com.muk.services.security.DefaultUaaLoginService.java
@Override public String approveClient(String approvalQuery, String cookie) { final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer()); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); final StringTokenizer cookieTokenizer = new StringTokenizer(cookie, "; "); while (cookieTokenizer.hasMoreTokens()) { headers.add(HttpHeaders.COOKIE, cookieTokenizer.nextToken()); }/*w w w . j a v a 2 s .co m*/ final MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); for (final String pair : approvalQuery.split("&")) { final String[] nv = pair.split("="); formData.add(nv[0], nv[1]); } formData.add("X-Uaa-Csrf", getCsrf(headers.get(HttpHeaders.COOKIE))); final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize") .build(); final ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.POST, formData, headers, String.class); if (approvalQuery.contains("false")) { return null; // approval declined. } // accepted, but location contains error if (response.getHeaders().getLocation().getQuery().startsWith("error")) { throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED, response.getHeaders().getLocation().getQuery()); } // accepted with related auth code return response.getHeaders().getLocation().getQuery().split("=")[1]; }