List of usage examples for com.squareup.okhttp Request urlString
public String urlString()
From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java
License:Open Source License
/** * Test get.//from w w w . j a v a 2 s.c o m */ @Test public void testGet() { final Request request = RequestBuilder.get(urlWithQuery).build(); assertEquals("GET", request.method()); assertEquals(urlWithQuery, request.urlString()); }
From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java
License:Open Source License
/** * Test post./* w w w .j a va 2 s . c o m*/ */ @Test public void testPost() { final Request request = RequestBuilder.post(url).build(); assertEquals("POST", request.method()); assertEquals(url, request.urlString()); }
From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java
License:Open Source License
/** * Test put./*from w ww . j av a2 s . c om*/ */ @Test public void testPut() { final Request request = RequestBuilder.put(urlWithQuery).build(); assertEquals("PUT", request.method()); assertEquals(urlWithQuery, request.urlString()); }
From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java
License:Open Source License
/** * Test using path url.// w w w.j a v a 2 s . c o m */ @Test public void testUsingPathUrl() { final String url = "/v1/ping"; final Request request = RequestBuilder.get(url).build(); assertEquals("GET", request.method()); assertTrue(RequestUtil.isRelative(request)); assertEquals(url, HttpUrl.parse(request.urlString()).encodedPath()); }
From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java
License:Open Source License
/** * Test with query object array.//from w w w .ja v a2s. co m */ @Test public void testWithQueryObjectArray() { final Request request = RequestBuilder.post(url).withQuery("foo", "bar", "p2", "p2").build(); assertEquals(urlWithQuery, request.urlString()); }
From source file:com.ibm.watson.developer_cloud.service.WatsonService.java
License:Open Source License
/** * Execute the HTTP request./*from ww w.ja va2 s .com*/ * * @param request the HTTP request * * @return the HTTP response */ protected Response execute(Request request) { final Builder builder = request.newBuilder(); // Set service endpoint for relative paths if (RequestUtil.isRelative(request)) { builder.url(RequestUtil.replaceEndPoint(request.urlString(), getEndPoint())); } // Set default headers if (defaultHeaders != null) { for (String key : defaultHeaders.names()) builder.header(key, defaultHeaders.get(key)); } // Set User-Agent builder.header(HttpHeaders.USER_AGENT, getUserAgent()); // Set Authentication setAuthentication(builder); final Request newRequest = builder.build(); Response response; log.log(Level.FINEST, "Request to: " + newRequest.urlString()); try { response = client.newCall(newRequest).execute(); } catch (final IOException e) { log.log(Level.SEVERE, "IOException", e); throw new RuntimeException(e); } if (response.isSuccessful()) { return response; } final int status = response.code(); // There was a Client Error 4xx or a Server Error 5xx // Get the error message and create the exception final String error = getErrorMessage(response); log.log(Level.SEVERE, newRequest.urlString() + ", status: " + status + ", error: " + error); switch (status) { case HttpStatus.BAD_REQUEST: // HTTP 400 throw new BadRequestException(error != null ? error : "Bad Request", response); case HttpStatus.UNAUTHORIZED: // HTTP 401 throw new UnauthorizedException("Unauthorized: Access is denied due to invalid credentials", response); case HttpStatus.FORBIDDEN: // HTTP 403 throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response); case HttpStatus.NOT_FOUND: // HTTP 404 throw new NotFoundException(error != null ? error : "Not found", response); case HttpStatus.NOT_ACCEPTABLE: // HTTP 406 throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response); case HttpStatus.CONFLICT: // HTTP 409 throw new ConflictException(error != null ? error : "", response); case HttpStatus.REQUEST_TOO_LONG: // HTTP 413 throw new RequestTooLargeException( error != null ? error : "Request too large: The request entity is larger than the server is able to process", response); case HttpStatus.UNSUPPORTED_MEDIA_TYPE: // HTTP 415 throw new UnsupportedException(error != null ? error : "Unsupported Media Type", response); case HttpStatus.TOO_MANY_REQUESTS: // HTTP 429 throw new TooManyRequestsException(error != null ? error : "Too many requests", response); case HttpStatus.INTERNAL_SERVER_ERROR: // HTTP 500 throw new InternalServerErrorException(error != null ? error : "Internal Server Error", response); case HttpStatus.SERVICE_UNAVAILABLE: // HTTP 503 throw new ServiceUnavailableException(error != null ? error : "Service Unavailable", response); default: // other errors throw new ServiceResponseException(status, error, response); } }
From source file:com.ibm.watson.developer_cloud.util.RequestUtil.java
License:Open Source License
/** * Checks if is relative./*from w ww. j a va 2s.c om*/ * * @param request the request * @return true, if is relative */ public static boolean isRelative(Request request) { return request.urlString().startsWith(DEFAULT_ENDPOINT); }
From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.GsonConverter.java
License:Apache License
private void parseCache(Request request, T object, String string, String mimeType) throws UnsupportedEncodingException { com.squareup.okhttp.CacheControl cacheControl = request.cacheControl(); if (cacheControl != null) { if (!cacheControl.noCache() && !cacheControl.noStore()) { if (object instanceof EAResult) { EAResult kResult = (EAResult) object; if (kResult != null && kResult.isSuccess()) { long now = System.currentTimeMillis(); long maxAge = cacheControl.maxAgeSeconds(); long softExpire = now + maxAge * 1000; System.out.println(":" + (softExpire - now) / 1000 + ""); Cache.Entry entry = new Cache.Entry(); entry.softTtl = softExpire; entry.ttl = entry.softTtl; // entry.serverDate = serverDate; // entry.responseHeaders = headers; entry.mimeType = mimeType; System.out.println("request.cacheControl()==" + request.cacheControl()); entry.data = string.getBytes(UTF8); cache.put(request.urlString(), entry); }//from w w w .ja va 2 s .co m } } } }
From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.KOkHttpCall.java
License:Apache License
private Response<T> execCacheRequest(Request request) { if (responseConverter instanceof GsonConverter) { GsonConverter<T> converter = (GsonConverter<T>) responseConverter; Cache cache = converter.getCache(); if (cache == null) { return null; }/*from w ww .j a v a2 s . co m*/ Entry entry = cache.get(request.urlString());// ?entry if (entry == null) { return null; } if (entry.isExpired()) {// return null; } if (entry.data != null) {// ? MediaType contentType = MediaType.parse(entry.mimeType); byte[] bytes = entry.data; try { com.squareup.okhttp.Response rawResponse = new com.squareup.okhttp.Response.Builder()// .code(200).request(request).protocol(Protocol.HTTP_1_1) .body(ResponseBody.create(contentType, bytes)).build(); return parseResponse(rawResponse, request); } catch (Exception e) { e.printStackTrace(); } } } return null; }
From source file:com.magnet.max.android.MaxRestAuthenticator.java
License:Apache License
@Override public Request authenticate(Proxy proxy, Response response) throws IOException { Request request = response.request(); String originalToken = AuthUtil.extractOAuthToken(request.header(AuthUtil.AUTHORIZATION_HEADER)); String authError = response.header(Response401.ERROR_HEADER); Log.e(TAG, "Got 401 for request : " + request.urlString() + " with token :\n" + originalToken + "\n error : " + authError); Response401 response401 = null; if (StringUtil.isNotEmpty(authError)) { response401 = new Response401(authError); }/*from ww w . j a va 2s . c om*/ final AtomicReference<String> refreshedToken = new AtomicReference<>(); String requestPath = request.httpUrl().encodedPath(); if (requestPath.endsWith("/")) { requestPath = requestPath.substring(0, requestPath.length() - 1); } if (requestPath.endsWith(RestConstants.APP_LOGIN_URL) || requestPath.endsWith(RestConstants.APP_LOGIN_WITH_DEVICE_URL)) { // App login failed, handle by callback in MagnetRestAdapter } else if (requestPath.endsWith(RestConstants.USER_LOGIN_URL) || requestPath.endsWith(RestConstants.USER_LOGOUT_URL)) { // User login failed, handle by callback in User.login } else if (requestPath.endsWith(RestConstants.USER_REFRESH_TOKEN_URL)) { // User token refresh failed MaxCore.userTokenInvalid(originalToken, null); } else if (null != response401 && response401.getErrorType() == Response401.AuthErrorType.CLIENT_ACCESS_TOKEN) { renewAppToken(refreshedToken); } else if (null != response401 && response401.getErrorType() == Response401.AuthErrorType.USER_ACCESS_TOKEN) { renewUserToken(refreshedToken); } else { if (null != response401) { if (response401.getErrorType() == Response401.AuthErrorType.USER_ACCESS_TOKEN) { MaxCore.userTokenInvalid(originalToken, null); } else { MaxCore.appTokenInvalid(originalToken, null); } } else { MaxCore.tokenInvalid(originalToken, null); } } // Reply the request with refreshed token if (null != refreshedToken.get()) { Log.d(TAG, "Using refreshed token : " + refreshedToken.get()); // Replace token Headers newHeaders = request.headers().newBuilder() .set(AuthUtil.AUTHORIZATION_HEADER, AuthUtil.generateOAuthToken(refreshedToken.get())).build(); return request.newBuilder().headers(newHeaders).build(); } else { Log.w(TAG, "No new token available, won't answer the challenge for " + request.urlString()); } return null; }