/** * Method to create http requests to services */ public default <I, O> ListenableFuture<ResponseEntity<O>> createRequest(final URIBuilder uri, final HttpMethod method, final I body, final Class<O> returnClazz, final HttpHeaders header) { final AsyncRestTemplate restTemplate = new AsyncRestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); if (header != null) { header.setContentType(MediaType.APPLICATION_JSON); } HttpEntity<?> entity; if (body != null) { entity = new HttpEntity<I>(body, header); } else { entity = new HttpEntity<String>(null, header); } return restTemplate.exchange(uri.toString(), method, entity, returnClazz); }
/** * Create the search proxy with the given elasticsearch host url. * * @param elasticSearchConnectionUrl the elasticsearch host url */ @Autowired @SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON") public SearchResource(String elasticSearchConnectionUrl) throws UnsupportedEncodingException, MalformedURLException { this.connectionUrl = elasticSearchConnectionUrl; URL url = new URL(elasticSearchConnectionUrl); restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); restTemplate.getMessageConverters() .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); String credentials = url.getUserInfo(); if (!StringUtils.isEmpty(credentials)) { byte[] plainCredsBytes = credentials.getBytes("UTF-8"); byte[] base64CredsBytes = Base64.encode(plainCredsBytes); base64Credentials = new String(base64CredsBytes, "UTF-8"); } // prevent throwing exception on error codes restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { protected boolean hasError(HttpStatus statusCode) { return false; } }); }
public void init() { HATEOAS_MEDIA_TYPE = MediaType.parseMediaType("application/hal+json"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new Jackson2HalModule()); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(HATEOAS_MEDIA_TYPE)); converter.setObjectMapper(mapper); hateoasRestTemplate = new RestTemplate(Arrays.<HttpMessageConverter<?>> asList(converter)); hateoasRestTemplate.setErrorHandler(new DefaultResponseErrorHandler()); //restTemplate = new RestTemplate(Arrays.<HttpMessageConverter<?>> asList(new MappingJackson2HttpMessageConverter())); //restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); }
public FacebookTokenServices() { restTemplate = new RestTemplate(); ((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() { @Override // Ignore 400 public void handleError( ClientHttpResponse response ) throws IOException { if (response.getRawStatusCode() != 400) { super.handleError(response); } } }); }
@Test @OAuth2ContextConfiguration(resource = InvalidClientCredentials.class, initialize = false) public void testInvalidCredentials() throws Exception { context.setAccessTokenProvider(new ClientCredentialsAccessTokenProvider() { @Override protected ResponseErrorHandler getResponseErrorHandler() { return new DefaultResponseErrorHandler() { public void handleError(ClientHttpResponse response) throws IOException { responseHeaders = response.getHeaders(); responseStatus = response.getStatusCode(); } }; } }); try { context.getAccessToken(); fail("Expected ResourceAccessException"); } catch (Exception e) { // ignore } // System.err.println(responseHeaders); String header = responseHeaders.getFirst("WWW-Authenticate"); assertTrue("Wrong header: " + header, header.contains("Basic realm")); assertEquals(HttpStatus.UNAUTHORIZED, responseStatus); }
public void handleError() { // handle error2 RestTemplate client = new RestTemplate(); ResponseErrorHandler responseErrorHandler = new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException { LOGGER.warn("response status: '{}', headers: '{}'", response.getStatusCode(), response.getHeaders()); } }; client.setErrorHandler(responseErrorHandler); client.exchange("http://localhost:8080/person/denied", HttpMethod.GET, null, String.class); }
/** * springboot初始化restTemplate */ @Bean public RestTemplate initRestTemplate() { // 长连接保持30秒 PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS); // 总连接数 pollingConnectionManager.setMaxTotal(1000); // 同路由的并发数 pollingConnectionManager.setDefaultMaxPerRoute(1000); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setConnectionManager(pollingConnectionManager); // 重试次数,默认是3次,没有开启 httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true)); // 保持长连接配置,需要在头添加Keep-Alive httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); RequestConfig.Builder builder = RequestConfig.custom(); builder.setConnectionRequestTimeout(200); builder.setConnectTimeout(5000); builder.setSocketTimeout(5000); RequestConfig requestConfig = builder.build(); httpClientBuilder.setDefaultRequestConfig(requestConfig); List<Header> headers = new ArrayList<>(); headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36")); headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate")); headers.add(new BasicHeader("Accept-Language", "zh-CN")); headers.add(new BasicHeader("Connection", "Keep-Alive")); httpClientBuilder.setDefaultHeaders(headers); HttpClient httpClient = httpClientBuilder.build(); // httpClient连接配置,底层是配置RequestConfig HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); // 连接超时 clientHttpRequestFactory.setConnectTimeout(5000); // 数据读取超时时间,即SocketTimeout clientHttpRequestFactory.setReadTimeout(5000); // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的 clientHttpRequestFactory.setConnectionRequestTimeout(200); // 缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。 clientHttpRequestFactory.setBufferRequestBody(false); // 添加内容转换器 List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(initStringHttpMessageConverter()); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new MappingJackson2XmlHttpMessageConverter()); messageConverters.add(new MappingJackson2HttpMessageConverter()); RestTemplate restTemplate = new RestTemplate(messageConverters); restTemplate.setRequestFactory(clientHttpRequestFactory); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); return restTemplate; }
@Before public void setup() { testRest.getRestTemplate().setErrorHandler(new DefaultResponseErrorHandler() { @Override public boolean hasError(ClientHttpResponse response) throws IOException { return response.getStatusCode() != HttpStatus.OK; } }); testRest.getRestTemplate().setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter(mapper))); }
/** * Gets the rest template. * * @return the rest template */ private RestTemplate getRestTemplate() { if (restTemplate == null) { restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create() .setDefaultHeaders(Arrays.asList(getBasicAuthenticateHeader())) .build())); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException { log.error("Response error: {} {}", response.getStatusCode(), response.getStatusText()); ErrorResponse errorResponse = null; try { errorResponse = objectMapper.readValue(response.getBody(), ErrorResponse.class); } catch (IOException ioe) { log.error("Fail to parse error", ioe); } if (errorResponse != null) { log.error("Response error object: {}", errorResponse); throw new ScalablePressBadRequestException(errorResponse); } super.handleError(response); } }); } return restTemplate; }
private GitHubClient(String accessToken) { this.restTemplate = new RestTemplate(); this.restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException { String errorMessage = "Unable to load Github Data:" + new String(getResponseBody(response), Charsets.UTF_8); LOGGER.error(errorMessage); throw new AuthenticationServiceException(errorMessage); } }); this.restTemplate.getInterceptors().add((request, body, execution) -> { request.getHeaders().add("Authorization", "bearer " + accessToken); return execution.execute(request, body); }); }
/** * Create a new {@link TestRestTemplate} instance with the specified credentials. * @param username the username to use (or {@code null}) * @param password the password (or {@code null}) * @param httpClientOptions client options to use if the Apache HTTP Client is used */ public TestRestTemplate(String username, String password, HttpClientOption... httpClientOptions) { if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) { setRequestFactory( new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions)); } addAuthentication(username, password); setErrorHandler(new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException { } }); }
public AssertingRestTemplate() { setErrorHandler(new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException { if (hasError(response)) { log.error("Response has status code [" + response.getStatusCode() + "] and text [" + response.getStatusText() + "])"); } } }); }
private RestTemplate getRestTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException { } }); return restTemplate; }
protected RestTemplate getRestTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { @Override public void handleError(ClientHttpResponse response) throws IOException { log.error(response.getStatusText()); } }); return restTemplate; }
@Test @OAuth2ContextConfiguration(resource = InvalidClientCredentials.class, initialize = false) public void testInvalidCredentialsWithFormAuthentication() throws Exception { resource.setClientAuthenticationScheme(AuthenticationScheme.form); context.setAccessTokenProvider(new ClientCredentialsAccessTokenProvider() { @Override protected ResponseErrorHandler getResponseErrorHandler() { return new DefaultResponseErrorHandler() { public void handleError(ClientHttpResponse response) throws IOException { responseHeaders = response.getHeaders(); responseStatus = response.getStatusCode(); } }; } }); try { context.getAccessToken(); fail("Expected ResourceAccessException"); } catch (Exception e) { // ignore } // System.err.println(responseHeaders); String header = responseHeaders.getFirst("WWW-Authenticate"); assertTrue("Wrong header: " + header, header.contains("Form realm")); assertEquals(HttpStatus.UNAUTHORIZED, responseStatus); }
@Test public void httpCustomStatus() throws MalformedURLException { expectedEx.expectMessage(equalTo("Server Error")); expectedEx.expect(JsonRpcClientException.class); RestTemplate restTemplate = new RestTemplate(); JsonRpcRestClient client = getClient(JettyServer.SERVLET, restTemplate); // Overwrite error handler for error check. restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); FakeServiceInterface service = ProxyUtil.createClientProxy(FakeServiceInterface.class, client); service.throwSomeException("function error"); }
private RestTemplate getRestTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { @Override public boolean hasError(ClientHttpResponse response) throws IOException { return false; } }); return restTemplate; }
private HttpClientTemplate() { // 长连接保持30秒 PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(timeToLive, TimeUnit.SECONDS); // 总连接数 pollingConnectionManager.setMaxTotal(maxTotal); // 同路由的并发数 pollingConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setConnectionManager(pollingConnectionManager); // 重试次数,默认是3次,没有开启 httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, requestSentRetryEnabled)); // 保持长连接配置,需要在头添加Keep-Alive httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); List<Header> headers = new ArrayList<>(); // 参考:http://www.cnblogs.com/sink_cup/archive/2011/03/15/http_user_agent.html // headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36")); // 不需要设置,可能会乱码,请参考:http://www.crifan.com/set_accept_encoding_header_to_gzip_deflate_return_messy_code/ // headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate")); // headers.add(new BasicHeader("Accept-Language", "zh-CN")); headers.add(new BasicHeader("Connection", "Keep-Alive")); httpClientBuilder.setDefaultHeaders(headers); HttpClient httpClient = httpClientBuilder.build(); // httpClient连接配置,底层是配置RequestConfig HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); // 连接超时 clientHttpRequestFactory.setConnectTimeout(connectTimeout); // 数据读取超时时间,即SocketTimeout clientHttpRequestFactory.setReadTimeout(readTimeout); // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的 clientHttpRequestFactory.setConnectionRequestTimeout(connectionRequestTimeout); // 缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。 if (!bufferRequestBody) { clientHttpRequestFactory.setBufferRequestBody(false); } // 添加内容转换器 // List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new FastJsonHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter(Charset.forName(charset))); messageConverters.add(new ByteArrayHttpMessageConverter()); super.setMessageConverters(messageConverters); super.setRequestFactory(clientHttpRequestFactory); super.setErrorHandler(new DefaultResponseErrorHandler()); }
@PostConstruct private void postConstruct() { restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); }
@PostConstruct private void postConstruct() { restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); restTemplate.setMessageConverters(httpMessageConverters.getConverters()); }
@PostConstruct private void postConstruct() { System.setProperty("spring.profiles.active", "test"); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); }
protected AbstractTwitterInboundChannelAdapter(TwitterTemplate twitter) { this.twitter = twitter; // Fix to get round TwitterErrorHandler not handling 401s etc. this.twitter.getRestTemplate().setErrorHandler(new DefaultResponseErrorHandler()); this.setPhase(Integer.MAX_VALUE); }
protected ResponseErrorHandler errorHandler() { return new DefaultResponseErrorHandler(); }
@Autowired public RestTemplateErrorLogger(DefaultResponseErrorHandler handler) { errorHandler = handler; }
@Bean public RestTemplate piwikRestTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new RestTemplateErrorLogger(new DefaultResponseErrorHandler())); return restTemplate; }
public ServerErrorHandler() { mHandler = new DefaultResponseErrorHandler(); mMapper = new Gson(); }
/** * Construct an error handler that can deal with OAuth2 concerns before handling the error in the default fashion. */ public OAuth2ErrorHandler(OAuth2ProtectedResourceDetails resource) { this(new DefaultResponseErrorHandler(), resource); }
@Override public String loginService(String code) { RestTemplate restTemplate = new RestTemplate(); JSONObject vars = new JSONObject(); vars.put("client_id", CLIENT_ID); vars.put("client_secret", CLIENT_SECRET); vars.put("code", code); // set headers HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(vars.toString(), headers); String result = restTemplate.postForObject(REDIRECT_URL, entity, String.class); // 올바르지 않은 code의 입력으로 access_token이 유효하지 않을 경우 try { JSONObject jsonObject = new JSONObject(result); String realResult = jsonObject.getString("access_token"); restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){ protected boolean hasError(HttpStatus statusCode) { return false; }}); String tokenResult = sendByGet(BASE_URL, realResult); JSONObject loginResult = new JSONObject(tokenResult); String login = loginResult.getString("login"); String id = loginResult.get("id").toString(); //최종 결과 JSON TYPE으로 반환 JSONObject returnResult = new JSONObject(); returnResult.put("login",login); returnResult.put("id",id); //MongoDB에 저장 - upsert() 로 값이 있으면 업데이트 없으면 새로 추가! Query query = new Query(); query.addCriteria(Criteria.where("id").is(id)); Update update = new Update(); update.set("id", id); update.set("login", login); mongoTemplate.upsert(query, update, User.class); // 나중에 예외처리 해줘야 할듯 return returnResult.toString(); }catch (Exception e){ JSONObject returnErrorResult = new JSONObject(); returnErrorResult.put("error","-1"); // 예외처리 시 // return org.json.JSONException: JSONObject["access_token"] not found. return returnErrorResult.toString(); } }