/** * @param request HTTP request to execute. * @param client The client used to execute the request. * @param responseClass Model class to unmarshal JSON body content. * @param fieldNamingPolicy FieldNamingPolicy for unmarshaling JSON. * @param errorTimeOut Number of milliseconds to re-send erroring requests. * @param maxRetries Number of times allowed to re-send erroring requests. */ public GaePendingResult( HTTPRequest request, URLFetchService client, Class<R> responseClass, FieldNamingPolicy fieldNamingPolicy, long errorTimeOut, Integer maxRetries, ExceptionsAllowedToRetry exceptionsAllowedToRetry) { this.request = request; this.client = client; this.responseClass = responseClass; this.fieldNamingPolicy = fieldNamingPolicy; this.errorTimeOut = errorTimeOut; this.maxRetries = maxRetries; this.exceptionsAllowedToRetry = exceptionsAllowedToRetry; this.call = client.fetchAsync(request); }
private boolean shouldRetry(HTTPResponse response) { return RETRY_ERROR_CODES.contains(response.getResponseCode()) && cumulativeSleepTime < errorTimeOut && (maxRetries == null || retryCounter < maxRetries); }
@Override public <T, R extends ApiResponse<T>> PendingResult<T> handlePost( String hostName, String url, String payload, String userAgent, Class<R> clazz, FieldNamingPolicy fieldNamingPolicy, long errorTimeout, Integer maxRetries, ExceptionsAllowedToRetry exceptionsAllowedToRetry) { FetchOptions fetchOptions = FetchOptions.Builder.withDeadline(10); HTTPRequest req = null; try { req = new HTTPRequest(new URL(hostName + url), HTTPMethod.POST, fetchOptions); req.setHeader(new HTTPHeader("Content-Type", "application/json; charset=utf-8")); req.setPayload(payload.getBytes(UTF_8)); } catch (MalformedURLException e) { LOG.error("Request: {}{}", hostName, url, e); throw (new RuntimeException(e)); } return new GaePendingResult<>( req, client, clazz, fieldNamingPolicy, errorTimeout, maxRetries, exceptionsAllowedToRetry); }
byte[] bytes = response.getContent(); R resp; for (HTTPHeader header : response.getHeaders()) { if (header.getName().equalsIgnoreCase("Content-Type")) { contentType = header.getValue(); && contentType.startsWith("image") && responseClass == ImageResult.Response.class && response.getResponseCode() == 200) { ImageResult result = new ImageResult(contentType, bytes); return (T) result; } catch (JsonSyntaxException e) { if (response.getResponseCode() > 399) { String.format( "Server Error: %d %s", response.getResponseCode(), new String(response.getContent(), Charset.defaultCharset())));
@Test(expected = IOException.class) public void fetchNonExistentLocalAppThrowsException() throws Exception { URL selfURL = new URL("BOGUS-" + appUrlBase + "/"); FetchOptions fetchOptions = FetchOptions.Builder.withDefaults() .doNotFollowRedirects() .setDeadline(10.0); HTTPRequest httpRequest = new HTTPRequest(selfURL, HTTPMethod.GET, fetchOptions); URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService(); HTTPResponse httpResponse = urlFetchService.fetch(httpRequest); fail("expected exception, got " + httpResponse.getResponseCode()); }
static HTTPRequest copyRequest(HTTPRequest in) { HTTPRequest out = new HTTPRequest(in.getURL(), in.getMethod(), in.getFetchOptions()); for (HTTPHeader h : in.getHeaders()) { out.addHeader(h); } out.setPayload(in.getPayload()); return out; } }
String pivotalUrl = "http://www.pivotaltracker.com/services/v3/projects/"+projectID+"/stories" String body = "<story><story_type>feature</story_type><name>Story name</name><requested_by>James Kirk</requested_by></story>" URLFetchService fetchService = URLFetchServiceFactory.getURLFetchService(); HTTPRequest request = new HTTPRequest(pivotalUrl, HTTPMethod.POST, FetchOptions.Builder.withDeadline(30)); request.addHeader(new HTTPHeader("X-TrackerToken","putTokenHere")); request.addHeader(new HTTPHeader("Content-type","application/xml")); HTTPResponse response = fetchService.fetch(request); if (response.getResponseCode() != 200) { // something went wrong }
String getHeader(HTTPResponse resp, String headerName) { for (HTTPHeader h : resp.getHeadersUncombined()) { if (headerName.equalsIgnoreCase(h.getName())) { return h.getValue(); } } return null; }
@Override public void addHeader(String name, String value) { request.addHeader(new HTTPHeader(name, value)); }
protected void testOptions(URL url, HTTPMethod method, FetchOptions options, ResponseHandler handler) throws Exception { HTTPRequest request = new HTTPRequest(url, method, options); URLFetchService service = URLFetchServiceFactory.getURLFetchService(); HTTPResponse response = service.fetch(request); handler.handle(response); }
/** * Returns a new instance of the default {@link FetchOptions} used by this requestor. This * method exists primarily since {@link FetchOptions} provides no copy methods. * * @return new instance of default fetch options used by this requestor. */ public static FetchOptions newDefaultOptions() { return FetchOptions.Builder.withDefaults() .validateCertificate() .doNotFollowRedirects() .disallowTruncate() // seconds .setDeadline((DEFAULT_CONNECT_TIMEOUT_MILLIS + DEFAULT_READ_TIMEOUT_MILLIS)/1000.0); }
@Override public <T, R extends ApiResponse<T>> PendingResult<T> handle( String hostName, String url, String userAgent, Class<R> clazz, FieldNamingPolicy fieldNamingPolicy, long errorTimeout, Integer maxRetries, ExceptionsAllowedToRetry exceptionsAllowedToRetry) { FetchOptions fetchOptions = FetchOptions.Builder.withDeadline(10); HTTPRequest req; try { req = new HTTPRequest(new URL(hostName + url), HTTPMethod.POST, fetchOptions); } catch (MalformedURLException e) { LOG.error("Request: {}{}", hostName, url, e); throw (new RuntimeException(e)); } return new GaePendingResult<>( req, client, clazz, fieldNamingPolicy, errorTimeout, maxRetries, exceptionsAllowedToRetry); }
@Override public void setTimeout(int connectTimeout, int readTimeout) { request.getFetchOptions().setDeadline( connectTimeout == 0 || readTimeout == 0 ? Double.MAX_VALUE : (connectTimeout + readTimeout) / 1000.0); }
private FetchOptions createFetchOptions(HttpRequestImpl request) { FetchOptions fetchOptions = FetchOptions.Builder.withDefaults(); fetchOptions = fetchOptions.setDeadline((double) request.getTimeout() / (double) 1000); return fetchOptions = request.isFollowRedirects() ? fetchOptions.followRedirects() : fetchOptions.doNotFollowRedirects(); }
HTTPRequestInfo(HTTPRequest req) { method = req.getMethod().toString(); byte[] payload = req.getPayload(); length = payload == null ? -1 : payload.length; url = req.getURL(); h1 = null; h2 = req.getHeaders(); }
/** Execute the specified {@code request} using the provided {@code urlFetchService}. */ protected HTTPResponse execute(URLFetchService urlFetchService, HTTPRequest request) throws IOException { return urlFetchService.fetch(request); }
String getHeader(HTTPResponse resp, String headerName) { for (HTTPHeader h : resp.getHeadersUncombined()) { if (headerName.equalsIgnoreCase(h.getName())) { return h.getValue(); } } return null; }
@Override public void addHeader(String name, String value) { request.addHeader(new HTTPHeader(name, value)); }
@Override public void setTimeout(int connectTimeout, int readTimeout) { request.getFetchOptions().setDeadline(connectTimeout == 0 || readTimeout == 0 ? Double.MAX_VALUE : (connectTimeout + readTimeout) / 1000.0); }
private T retry() throws IOException, ApiException, InterruptedException { retryCounter++; LOG.info("Retrying request. Retry #{}", retryCounter); this.call = client.fetchAsync(request); return this.await(); }