@Autowired public NauticalWarningController(@Value("${ais.pooki.url}") final String pookiUrl) { this.pookiUrl = pookiUrl; template = new RestTemplate(); // template.getMessageConverters().add(new ByteArrayHttpMessageConverter()); template.setErrorHandler(new NauticalWarningErrorHandler()); }
/** * Factory method for a secure RestTemplate with Basic authentication that does not follow * redirects, ignores cookies and does not throw exceptions on server side errors. * * @return a basic RestTemplate with Basic authentication */ public static RestTemplate get(final String username, final String password) { List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); if (username != null) { interceptors.add( new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept( HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { byte[] token = Base64.encode((username + ":" + password).getBytes()); request.getHeaders().add("Authorization", "Basic " + new String(token)); return execution.execute(request, body); } }); } RestTemplate restTemplate = new RestTemplate( new InterceptingClientHttpRequestFactory( new SimpleClientHttpRequestFactory(), interceptors)); if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) { new HttpComponentsCustomizer().customize(restTemplate); } restTemplate.setErrorHandler( new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException {} }); return restTemplate; }
@Override protected void onHandleIntent(Intent intent) { ApplicationController app = ((ApplicationController) getApplicationContext()); UsuarioDTO user = app.getUserLogin(); Map<String, Integer> parms = new HashMap<String, Integer>(); parms.put("id", user.getId()); restTemp.setErrorHandler(new RestResponseErrorHandler<String>(String.class)); Intent intentBack = new Intent(Constantes.GET_AMIGOS_FILTRO_ACTION); try { UsuarioDTO[] respuesta = restTemp.getForObject(Constantes.GET_AMIGOS_SERVICE_URL, UsuarioDTO[].class, parms); intentBack.putExtra("respuesta", Util.getArrayListUsuarioDTO(respuesta)); } catch (RestResponseException e) { String msg = e.getMensaje(); intentBack.putExtra("error", msg); } catch (ResourceAccessException e) { Log.e(TAG, e.getMessage()); intentBack.putExtra("error", Constantes.MSG_ERROR_TIMEOUT); } this.sendBroadcast(intentBack); }
@Test public void testOverwriteContentTypeHeader() { HttpMessageSender messageSender = new HttpMessageSender(); String requestUrl = "http://localhost:8088/test"; final String responseBody = "<TestResponse><Message>Hello World!</Message></TestResponse>"; messageSender.setReplyMessageHandler(replyMessageHandler); messageSender.setRequestMethod(HttpMethod.POST); messageSender.setRequestUrl(requestUrl); messageSender.setContentType("text/xml"); messageSender.setCharset("ISO-8859-1"); Message<?> requestMessage = MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>") .setHeader("Content-Type", "application/xml;charset=UTF-8") .setHeader("Accept", "application/xml") .build(); messageSender.setRestTemplate(restTemplate); reset(restTemplate, replyMessageHandler); restTemplate.setErrorHandler(anyObject(ResponseErrorHandler.class)); expectLastCall().once(); expect( restTemplate.exchange( eq(requestUrl), eq(HttpMethod.POST), anyObject(HttpEntity.class), eq(String.class))) .andAnswer( new IAnswer<ResponseEntity<String>>() { public ResponseEntity<String> answer() throws Throwable { HttpEntity<?> httpRequest = (HttpEntity<?>) getCurrentArguments()[2]; Assert.assertEquals( httpRequest.getBody().toString(), "<TestRequest><Message>Hello World!</Message></TestRequest>"); Assert.assertEquals(httpRequest.getHeaders().size(), 2); Assert.assertEquals( httpRequest.getHeaders().getContentType().toString(), "application/xml;charset=UTF-8"); Assert.assertEquals( httpRequest.getHeaders().getAccept().get(0).toString(), "application/xml"); return new ResponseEntity<String>(responseBody, HttpStatus.OK); } }) .once(); replyMessageHandler.onReplyMessage(anyObject(Message.class)); expectLastCall().once(); replay(restTemplate, replyMessageHandler); messageSender.send(requestMessage); verify(restTemplate, replyMessageHandler); }
/** * Upload an app using the legacy API used for older vcap versions like Micro Cloud Foundry 1.1 * and older As of Micro Cloud Foundry 1.2 and for any recent CloudFoundry.com deployment the * current method of setting the content type as JSON works fine. * * @param path app path * @param entity HttpEntity for the payload * @param appName name of app * @throws HttpServerErrorException */ private void uploadAppUsingLegacyApi(String path, HttpEntity<?> entity, String appName) throws HttpServerErrorException { RestTemplate legacyRestTemplate = new RestTemplate(); legacyRestTemplate.setRequestFactory(this.getRestTemplate().getRequestFactory()); legacyRestTemplate.setErrorHandler(new ErrorHandler()); legacyRestTemplate.setMessageConverters(getLegacyMessageConverters()); legacyRestTemplate.put(path, entity, appName); }
private RestTemplate getRestTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler( new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException {} }); return restTemplate; }
private void setRestTemplateParams(Map<String, Object> clientParams) { int maxConnPerRoute = DEFAULT_MAX_CONN_PER_ROUTE; int maxConnTotal = DEFAULT_MAX_CONN_TOTAL; int connectTimeoutInMs = DEFAULT_CONNECT_TIMEOUT_IN_MS; if (clientParams.containsKey(DEFAULT_URI_VARIABLES.value)) { restTemplate.setDefaultUriVariables( (Map<String, ?>) clientParams.get(DEFAULT_URI_VARIABLES.value)); } if (clientParams.containsKey(ERROR_HANDLER.value)) { restTemplate.setErrorHandler((ResponseErrorHandler) clientParams.get(ERROR_HANDLER.value)); } if (clientParams.containsKey(MESSAGE_CONVERTERS.value)) { restTemplate.setMessageConverters( (List<HttpMessageConverter<?>>) clientParams.get(MESSAGE_CONVERTERS.value)); } if (clientParams.containsKey(URI_TEMPLATE_HANDLER.value)) { restTemplate.setUriTemplateHandler( (UriTemplateHandler) clientParams.get(URI_TEMPLATE_HANDLER.value)); } if (clientParams.containsKey(INTERCEPTORS.value)) { restTemplate.setInterceptors( (List<ClientHttpRequestInterceptor>) clientParams.get(INTERCEPTORS.value)); } if (clientParams.containsKey(MAX_CONN_PER_ROUTE.value)) { Object value = clientParams.get(MAX_CONN_PER_ROUTE.value); if (value instanceof String) maxConnPerRoute = Integer.parseInt((String) value); else maxConnPerRoute = (int) value; } if (clientParams.containsKey(MAX_CONN_TOTAL.value)) { Object value = clientParams.get(MAX_CONN_TOTAL.value); if (value instanceof String) maxConnTotal = Integer.parseInt((String) value); else maxConnTotal = (int) value; } if (clientParams.containsKey(CONNECT_TIMEOUT_IN_MS.value)) { Object value = clientParams.get(CONNECT_TIMEOUT_IN_MS.value); if (value instanceof String) connectTimeoutInMs = Integer.parseInt((String) value); else connectTimeoutInMs = (int) value; } if (clientParams.containsKey(REQUEST_FACTORY.value)) { restTemplate.setRequestFactory( (ClientHttpRequestFactory) clientParams.get(REQUEST_FACTORY.value)); } if (!clientParams.containsKey(REQUEST_FACTORY.value) && containsAnyRequestFactoryParam(clientParams)) { restTemplate.setRequestFactory( getRequestFactory(maxConnPerRoute, maxConnTotal, connectTimeoutInMs)); } else if (clientParams.containsKey(REQUEST_FACTORY.value) && containsAnyRequestFactoryParam(clientParams)) { throw new IllegalArgumentException( "Parameters max_conn_total, max_conn_per_route and connect_timeout cannot be set if " + "request_factory parameter presents. You must configure these parameters in your request_factory entity."); } }
@Test public void testErrorResponsePropagateStrategy() { HttpMessageSender messageSender = new HttpMessageSender(); String requestUrl = "http://localhost:8088/test"; final String responseBody = "<TestResponse><Message>Hello World!</Message></TestResponse>"; messageSender.setReplyMessageHandler(replyMessageHandler); messageSender.setRequestMethod(HttpMethod.POST); messageSender.setRequestUrl(requestUrl); messageSender.setErrorHandlingStrategy(ErrorHandlingStrategy.PROPAGATE); Message<?> requestMessage = MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>") .build(); messageSender.setRestTemplate(restTemplate); reset(restTemplate, replyMessageHandler); restTemplate.setErrorHandler(anyObject(ResponseErrorHandler.class)); expectLastCall().once(); expect( restTemplate.exchange( eq(requestUrl), eq(HttpMethod.POST), anyObject(HttpEntity.class), eq(String.class))) .andReturn(new ResponseEntity<String>(responseBody, HttpStatus.FORBIDDEN)) .once(); replyMessageHandler.onReplyMessage(anyObject(Message.class)); expectLastCall() .andAnswer( new IAnswer<Object>() { public Object answer() throws Throwable { Message<?> responseMessage = (Message<?>) getCurrentArguments()[0]; Assert.assertEquals( responseMessage.getHeaders().get(CitrusHttpMessageHeaders.HTTP_STATUS_CODE), HttpStatus.FORBIDDEN); Assert.assertEquals( responseMessage.getHeaders().get(CitrusHttpMessageHeaders.HTTP_REASON_PHRASE), "FORBIDDEN"); return null; } }) .once(); replay(restTemplate, replyMessageHandler); messageSender.send(requestMessage); verify(restTemplate, replyMessageHandler); }
@Test public void testOverwriteRequestMethod() { HttpMessageSender messageSender = new HttpMessageSender(); String requestUrl = "http://localhost:8088/test"; final String responseBody = "<TestResponse><Message>Hello World!</Message></TestResponse>"; messageSender.setReplyMessageHandler(replyMessageHandler); messageSender.setRequestMethod(HttpMethod.GET); messageSender.setRequestUrl(requestUrl); Message<?> requestMessage = MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>") .setHeader(CitrusHttpMessageHeaders.HTTP_REQUEST_METHOD, "GET") .build(); messageSender.setRestTemplate(restTemplate); reset(restTemplate, replyMessageHandler); restTemplate.setErrorHandler(anyObject(ResponseErrorHandler.class)); expectLastCall().once(); expect( restTemplate.exchange( eq(requestUrl), eq(HttpMethod.GET), anyObject(HttpEntity.class), eq(String.class))) .andAnswer( new IAnswer<ResponseEntity<String>>() { public ResponseEntity<String> answer() throws Throwable { HttpEntity<?> httpRequest = (HttpEntity<?>) getCurrentArguments()[2]; Assert.assertNull(httpRequest.getBody()); // null because of GET Assert.assertEquals(httpRequest.getHeaders().size(), 1); Assert.assertEquals( httpRequest.getHeaders().getContentType().toString(), "text/plain;charset=UTF-8"); return new ResponseEntity<String>(responseBody, HttpStatus.OK); } }) .once(); replyMessageHandler.onReplyMessage(anyObject(Message.class)); expectLastCall().once(); replay(restTemplate, replyMessageHandler); messageSender.send(requestMessage); verify(restTemplate, replyMessageHandler); }
@Bean(name = "restTemplate") public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(httpClientFactory()); restTemplate.setErrorHandler(new RestTemplateErrorHandler()); List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); converters.add(new FormHttpMessageConverter()); converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); converters.add(new MappingJacksonHttpMessageConverter()); converters.add(new Jaxb2RootElementHttpMessageConverter()); restTemplate.setMessageConverters(converters); return restTemplate; }
public RestaurantRestClient(String urlStub) { httpClient.getHttpConnectionManager().getParams().setMaxTotalConnections(10); httpClient .getHttpConnectionManager() .getParams() .setMaxConnectionsPerHost(httpClient.getHostConfiguration(), 10); restClient.setErrorHandler(new MyErrorHandler()); this.urlStub = urlStub; // List<HttpMessageConverter<?>> converters = new ArrayList<>(); // converters.add(converter); // restClient.setMessageConverters(converters); // http://localhost:8888/app/backbone/restaurant/ }
private <T extends JovianResponse> T execute( String url, Map<String, String> params, Class<T> clazz, HttpMethod method) throws JovianException { // 自定义错误处理 CustomErrorHandler errorHandler = new CustomErrorHandler(); restTemplate.setErrorHandler(errorHandler); // 添加消息转换器 List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new FormHttpMessageConverter()); restTemplate.setMessageConverters(messageConverters); String rsp = ""; try { switch (method) { case POST: rsp = restTemplate.postForObject(url, generateFormValues(params), String.class); break; case GET: if (params.size() > 0) { url += "?" + generateGetUrl(params); } rsp = restTemplate.getForObject(url, String.class); break; default: break; } } catch (RestClientException e) { throw new JovianException(1, "网络访问异常"); } T response = null; errorHandler.getStatusCode(); Converter converter = new JacsonJsonConverter(); switch (errorHandler.getStatusCode()) { case OK: // convert rsp to Object; response = converter.convertResponse2Object(rsp, clazz); break; case BAD_REQUEST: ErrorResponse errorResponse = converter.convertResponse2Object(rsp, ErrorResponse.class); throw new JovianException( errorResponse.getErrorCode(), errorResponse.getErrorMsg(), errorResponse.getSubMsg()); case NOT_FOUND: throw new JovianException(2, url + " 访问的资源不存在"); default: throw new JovianException(2, "服务不可用"); } return response; }
@Before public void createRestTemplate() throws Exception { client = (OAuth2RestTemplate) serverRunning.getRestTemplate(); client.setErrorHandler( new OAuth2ErrorHandler(context.getResource()) { // Pass errors through in response entity for status code analysis @Override public boolean hasError(ClientHttpResponse response) throws IOException { return false; } @Override public void handleError(ClientHttpResponse response) throws IOException {} }); }
@Test public void testEndpointUriResolver() { HttpMessageSender messageSender = new HttpMessageSender(); String requestUrl = "http://localhost:8088/test"; String responseBody = "<TestResponse><Message>Hello World!</Message></TestResponse>"; messageSender.setReplyMessageHandler(replyMessageHandler); messageSender.setRequestMethod(HttpMethod.GET); messageSender.setRequestUrl(requestUrl); Message<?> requestMessage = MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>") .build(); EndpointUriResolver endpointUriResolver = EasyMock.createMock(EndpointUriResolver.class); messageSender.setEndpointUriResolver(endpointUriResolver); messageSender.setRestTemplate(restTemplate); reset(restTemplate, replyMessageHandler, endpointUriResolver); restTemplate.setErrorHandler(anyObject(ResponseErrorHandler.class)); expectLastCall().once(); expect(endpointUriResolver.resolveEndpointUri(requestMessage, "http://localhost:8088/test")) .andReturn("http://localhost:8081/new") .once(); expect( restTemplate.exchange( eq("http://localhost:8081/new"), eq(HttpMethod.GET), anyObject(HttpEntity.class), eq(String.class))) .andReturn(new ResponseEntity<String>(responseBody, HttpStatus.OK)) .once(); replyMessageHandler.onReplyMessage(anyObject(Message.class)); expectLastCall().once(); replay(restTemplate, replyMessageHandler, endpointUriResolver); messageSender.send(requestMessage); verify(restTemplate, replyMessageHandler, endpointUriResolver); }
@Override protected void onHandleIntent(Intent intent) { String pass = intent.getStringExtra("pass"); String email = intent.getStringExtra("email"); Intent intentLogin = new Intent(Constantes.LOGIN_FILTRO_ACTION); try { Map<String, String> parms = new HashMap<String, String>(); parms.put("email", email); parms.put("pass", pass); restTemp.setErrorHandler(new RestResponseErrorHandler<String>(String.class)); UsuarioDTO user = restTemp.getForObject(Constantes.LOGIN_SERVICE_URL, UsuarioDTO.class, parms); if (user.getEmail() != null) { ApplicationController app = ((ApplicationController) getApplicationContext()); app.setUserLogin(user); // ///////////////////////////////////////////////// // Cargo las categorias CategoriaDTO[] respuesta = restTemp.getForObject(Constantes.GET_CATEGORIAS_SERVICE_URL, CategoriaDTO[].class); CategoriasUtil.cargarCategorias(this, Util.getArrayListCategoriaDTO(respuesta)); // /////////////////////////////////////////////// } intentLogin.putExtra("usuario", user); sendBroadcast(intentLogin); } catch (RestResponseException e) { intentLogin.putExtra("error", (String) e.getResponseEntity().getBody()); Log.e(TAG, (String) e.getResponseEntity().getBody()); sendBroadcast(intentLogin); } catch (ResourceAccessException e) { intentLogin.putExtra("error", Constantes.MSG_ERROR_TIMEOUT); Log.e(TAG, e.getMessage()); sendBroadcast(intentLogin); } }
@Test public void testErrorResponseExceptionStrategy() { HttpMessageSender messageSender = new HttpMessageSender(); String requestUrl = "http://localhost:8088/test"; messageSender.setReplyMessageHandler(replyMessageHandler); messageSender.setRequestMethod(HttpMethod.POST); messageSender.setRequestUrl(requestUrl); messageSender.setErrorHandlingStrategy(ErrorHandlingStrategy.THROWS_EXCEPTION); Message<?> requestMessage = MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>") .build(); messageSender.setRestTemplate(restTemplate); reset(restTemplate, replyMessageHandler); restTemplate.setErrorHandler(anyObject(ResponseErrorHandler.class)); expectLastCall().once(); expect( restTemplate.exchange( eq(requestUrl), eq(HttpMethod.POST), anyObject(HttpEntity.class), eq(String.class))) .andThrow(new HttpClientErrorException(HttpStatus.FORBIDDEN)) .once(); replay(restTemplate, replyMessageHandler); try { messageSender.send(requestMessage); Assert.fail("Missing exception due to http error status code"); } catch (HttpClientErrorException e) { Assert.assertEquals(e.getMessage(), "403 FORBIDDEN"); verify(restTemplate, replyMessageHandler); } }
public RestOperations createRestTemplate() { RestTemplate client = new RestTemplate(); client.setRequestFactory( new SimpleClientHttpRequestFactory() { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { super.prepareConnection(connection, httpMethod); connection.setInstanceFollowRedirects(false); } }); client.setErrorHandler( new ResponseErrorHandler() { // Pass errors through in response entity for status code analysis public boolean hasError(ClientHttpResponse response) throws IOException { return false; } public void handleError(ClientHttpResponse response) throws IOException {} }); return client; }
public boolean run(PostmanRequest request, PostmanRunResult runResult) { runPrerequestScript(request, runResult); HttpHeaders headers = request.getHeaders(var); if (request.dataMode.equals("urlencoded")) { headers.set("Content-Type", "application/x-www-form-urlencoded"); } String requestId = headers.getFirst(REQUEST_ID_HEADER); if (requestId == null) { requestId = UUID.randomUUID().toString(); headers.set(REQUEST_ID_HEADER, requestId); } System.out.println("===============> requestId:" + requestId); HttpEntity<String> entity = new HttpEntity<String>(request.getData(var), headers); ResponseEntity<String> httpResponse = null; PostmanErrorHandler errorHandler = new PostmanErrorHandler(haltOnError); RestTemplate restTemplate = setupRestTemplate(request); restTemplate.setErrorHandler(errorHandler); String url = request.getUrl(var); URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { if (haltOnError) throw new HaltTestFolderException(); else return false; } long startMillis = System.currentTimeMillis(); httpResponse = restTemplate.exchange(uri, HttpMethod.valueOf(request.method), entity, String.class); System.out.println(" [" + (System.currentTimeMillis() - startMillis) + "ms]"); // NOTE: there are certain negative test cases that expect 5xx series // response code. return this.evaluateTests(request, httpResponse, runResult); }
public RestTemplate getRestTemplate() { RestTemplate client = new RestTemplate(); CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory() { @Override protected void postProcessCommonsHttpMethod(HttpMethodBase httpMethod) { httpMethod.setFollowRedirects(false); // We don't want stateful conversations for this test httpMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); } }; client.setRequestFactory(requestFactory); client.setErrorHandler( new ResponseErrorHandler() { // Pass errors through in response entity for status code analysis public boolean hasError(ClientHttpResponse response) throws IOException { return false; } public void handleError(ClientHttpResponse response) throws IOException {} }); return client; }
/** * @see com.consol.citrus.message.MessageSender#send(org.springframework.integration.Message) * @throws CitrusRuntimeException */ public void send(Message<?> message) { String endpointUri; if (endpointUriResolver != null) { endpointUri = endpointUriResolver.resolveEndpointUri(message, getRequestUrl()); } else { endpointUri = getRequestUrl(); } log.info("Sending HTTP message to: '" + endpointUri + "'"); if (log.isDebugEnabled()) { log.debug("Message to be sent:\n" + message.getPayload().toString()); } HttpMethod method = requestMethod; if (message.getHeaders().containsKey(CitrusHttpMessageHeaders.HTTP_REQUEST_METHOD)) { method = HttpMethod.valueOf( (String) message.getHeaders().get(CitrusHttpMessageHeaders.HTTP_REQUEST_METHOD)); } HttpEntity<?> requestEntity = generateRequest(message, method); restTemplate.setErrorHandler(new InternalResponseErrorHandler(message)); ResponseEntity<?> response = restTemplate.exchange(endpointUri, method, requestEntity, String.class); log.info("HTTP message was successfully sent to endpoint: '" + endpointUri + "'"); informReplyMessageHandler( buildResponseMessage( response.getHeaders(), response.getBody() != null ? response.getBody() : "", response.getStatusCode()), message); }
public SpringBasedHttpClient() { clientParams = new HashMap<>(); restTemplate = new RestTemplate(); restTemplate.setRequestFactory(getRequestFactory()); restTemplate.setErrorHandler(new AllowAllCodesResponseErrorHandler()); }