Example #1
0
 @Test
 public void put() {
   Request request = fromArgs("-X", "PUT", "http://example.com").createRequest();
   assertEquals("PUT", request.method());
   assertEquals("http://example.com", request.urlString());
   assertNull(request.body());
 }
 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);
         }
       }
     }
   }
 }
Example #3
0
  public static RouteSelector get(Request request, OkHttpClient client, Dns dns)
      throws IOException {
    String uriHost = request.url().getHost();
    if (uriHost == null || uriHost.length() == 0) {
      throw new UnknownHostException(request.url().toString());
    }

    SSLSocketFactory sslSocketFactory = null;
    HostnameVerifier hostnameVerifier = null;
    if (request.isHttps()) {
      sslSocketFactory = client.getSslSocketFactory();
      hostnameVerifier = client.getHostnameVerifier();
    }

    Address address =
        new Address(
            uriHost,
            getEffectivePort(request.url()),
            client.getSocketFactory(),
            sslSocketFactory,
            hostnameVerifier,
            client.getAuthenticator(),
            client.getProxy(),
            client.getProtocols());

    return new RouteSelector(address, request.uri(), dns, client, request);
  }
 @Override
 public Map<String, String> getAllHeaders() {
   HashMap<String, String> headers = new HashMap<>();
   for (String key : request.headers().names()) {
     headers.put(key, request.header(key));
   }
   return headers;
 }
Example #5
0
 @Test
 public void userAgent() {
   Request request = fromArgs("-A", "foo", "http://example.com").createRequest();
   assertEquals("GET", request.method());
   assertEquals("http://example.com", request.urlString());
   assertEquals("foo", request.header("User-Agent"));
   assertNull(request.body());
 }
Example #6
0
 @Test
 public void referer() {
   Request request = fromArgs("-e", "foo", "http://example.com").createRequest();
   assertEquals("GET", request.method());
   assertEquals("http://example.com", request.urlString());
   assertEquals("foo", request.header("Referer"));
   assertNull(request.body());
 }
 @Override
 public String getContentType() {
   if (request.body() != null) {
     return (request.body().contentType() != null)
         ? request.body().contentType().toString()
         : null;
   }
   return null;
 }
 @Override
 public InputStream getMessagePayload() throws IOException {
   if (request.body() == null) {
     return null;
   }
   Buffer buf = new Buffer();
   request.body().writeTo(buf);
   return buf.inputStream();
 }
Example #9
0
 @Test
 public void dataPut() {
   Request request = fromArgs("-d", "foo", "-X", "PUT", "http://example.com").createRequest();
   Request.Body body = request.body();
   assertEquals("PUT", request.method());
   assertEquals("http://example.com", request.urlString());
   assertEquals("application/x-form-urlencoded; charset=utf-8", body.contentType().toString());
   assertEquals("foo", bodyAsString(body));
 }
  private static String bodyToString(final Request request) {

    try {
      final Request copy = request.newBuilder().build();
      final Buffer buffer = new Buffer();
      copy.body().writeTo(buffer);
      return buffer.readUtf8();
    } catch (final IOException e) {
      return "did not work";
    }
  }
Example #11
0
 @Test
 public void contentTypeHeader() {
   Request request =
       fromArgs("-d", "foo", "-H", "Content-Type: application/json", "http://example.com")
           .createRequest();
   Request.Body body = request.body();
   assertEquals("POST", request.method());
   assertEquals("http://example.com", request.urlString());
   assertEquals("application/json; charset=utf-8", body.contentType().toString());
   assertEquals("foo", bodyAsString(body));
 }
  KubernetesClientException requestException(Request request, Exception e) {
    StringBuilder sb = new StringBuilder();
    sb.append("Error executing: ")
        .append(request.method())
        .append(" at: ")
        .append(request.urlString())
        .append(". Cause: ")
        .append(e.getMessage());

    return new KubernetesClientException(sb.toString(), e);
  }
 private OkHttpClient createOkHttpClient() {
   OkHttpClient client = new OkHttpClient();
   client
       .interceptors()
       .add(
           chain -> {
             Request request = chain.request();
             Request newRequest =
                 request.newBuilder().addHeader("Cookie", "auth_token=" + authToken).build();
             return chain.proceed(newRequest);
           });
   return client;
 }
Example #14
0
 static String get(Request request, java.net.Proxy.Type type, Protocol protocol) {
   StringBuilder stringbuilder = new StringBuilder();
   stringbuilder.append(request.method());
   stringbuilder.append(' ');
   if (includeAuthorityInRequestLine(request, type)) {
     stringbuilder.append(request.url());
   } else {
     stringbuilder.append(requestPath(request.url()));
   }
   stringbuilder.append(' ');
   stringbuilder.append(version(protocol));
   return stringbuilder.toString();
 }
  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    TwitterOauthHelper oauthHelper = TwitterOauthHelper.get();

    try {
      String authHeaderString = oauthHelper.getAuthorizationHeaderString(request);
      request = request.newBuilder().addHeader(AUTH_HEADER, authHeaderString).build();
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
      Log.e(TAG, "Failed to get auth header string", e);
    }

    return chain.proceed(request);
  }
 @Override
 public Response intercept(Chain chain) throws IOException {
   Request originalRequest = chain.request();
   Request.Builder request = originalRequest.newBuilder();
   if (originalRequest.header("fresh") != null) {
     request.cacheControl(CacheControl.FORCE_NETWORK);
   }
   Response response = chain.proceed(request.build());
   return response
       .newBuilder()
       .removeHeader("Pragma")
       .removeHeader("Cache-Control")
       .header("Cache-Control", cacheControl())
       .build();
 }
Example #17
0
 private Connection createNextConnection()
 {
     Object obj = client.getConnectionPool();
     do
     {
         Connection connection1 = ((ConnectionPool) (obj)).get(address);
         if (connection1 == null)
         {
             break;
         }
         if (networkRequest.method().equals("GET") || Internal.instance.isReadable(connection1))
         {
             return connection1;
         }
         Util.closeQuietly(connection1.getSocket());
     } while (true);
     try
     {
         obj = new Connection(((ConnectionPool) (obj)), routeSelector.next());
     }
     catch (IOException ioexception)
     {
         throw new RouteException(ioexception);
     }
     return ((Connection) (obj));
 }
Example #18
0
 private void maybeCache()
 {
     Object obj = Internal.instance.internalCache(client);
     if (obj != null)
     {
         if (!CacheStrategy.isCacheable(userResponse, networkRequest))
         {
             if (HttpMethod.invalidatesCache(networkRequest.method()))
             {
                 try
                 {
                     ((InternalCache) (obj)).remove(networkRequest);
                     return;
                 }
                 // Misplaced declaration of an exception variable
                 catch (Object obj)
                 {
                     return;
                 }
             }
         } else
         {
             storeRequest = ((InternalCache) (obj)).put(stripBody(userResponse));
             return;
         }
     }
 }
Example #19
0
 /**
  * @param context
  * @param bundle
  */
 public AbstractBaseOkHttp(@NonNull Context context, @NonNull Bundle bundle) {
   this.context = context;
   this.bundle = bundle;
   printLog = new PrintLog();
   printLog.setRequestTime(
       TimeUtils.getCurrentTimeInString(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒")));
   request = getRequest();
   printLog.setUrl(request.urlString());
   printLog.setHeaders(
       new StringBuilder()
           .append(CONTENT_TYPE_KEY)
           .append("=")
           .append(request.header(CONTENT_TYPE_KEY))
           .toString());
   execute(getOkHttpClient(), getRequest(), getResponseCallBack());
 }
 private void logRequest(Request request, Response response, String body) throws IOException {
   if (Config.LOGS_ENABLED) {
     String requestString = request.method() + " " + request.urlString();
     if (!request.method().toLowerCase().equals("get")) {
       Buffer buffer = new Buffer();
       request.body().writeTo(buffer);
       requestString += " " + buffer.readUtf8();
     }
     if (response.code() >= 400) {
       LogHelper.d(TAG, "request failed " + requestString);
     } else {
       LogHelper.d(TAG, "request success " + requestString);
     }
     LogHelper.i(TAG, "response = " + response.code() + "  " + body);
   }
 }
  @Override
  protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {
    OkHttpClient requestScopedClient = globalClient.clone();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));

    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();
    for (String header : responseHeaders.names()) {
      headerBuilder.putAll(header, responseHeaders.values(header));
    }

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
      response.body().close();
    } else {
      Payload payload = newInputStreamPayload(response.body().byteStream());
      contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
      builder.payload(payload);
    }

    builder.headers(filterOutContentHeaders(headers));

    return builder.build();
  }
 @Override
 protected Call enqueue(Request request, com.squareup.okhttp.Callback requestCallback) {
   Context context = PopcornApplication.getAppContext();
   PackageInfo pInfo;
   String versionName = "0.0.0";
   try {
     pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
     versionName = pInfo.versionName;
   } catch (PackageManager.NameNotFoundException e) {
     e.printStackTrace();
   }
   request =
       request
           .newBuilder()
           .removeHeader("User-Agent")
           .addHeader(
               "User-Agent",
               String.format(
                   "Mozilla/5.0 (Linux; U; Android %s; %s; %s Build/%s) AppleWebkit/534.30 (KHTML, like Gecko) PT/%s",
                   Build.VERSION.RELEASE,
                   LocaleUtils.getCurrent(),
                   Build.MODEL,
                   Build.DISPLAY,
                   versionName))
           .build();
   return super.enqueue(request, requestCallback);
 }
Example #23
0
  /**
   * Returns the next connection to attempt.
   *
   * @throws NoSuchElementException if there are no more routes to attempt.
   */
  Connection nextUnconnected() throws IOException {
    // Always prefer pooled connections over new connections.
    for (Connection pooled; (pooled = pool.get(address)) != null; ) {
      if (request.method().equals("GET") || Internal.instance.isReadable(pooled)) return pooled;
      pooled.getSocket().close();
    }

    // Compute the next route to attempt.
    if (!hasNextTlsVersion()) {
      if (!hasNextInetSocketAddress()) {
        if (!hasNextProxy()) {
          if (!hasNextPostponed()) {
            throw new NoSuchElementException();
          }
          return new Connection(pool, nextPostponed());
        }
        lastProxy = nextProxy();
        resetNextInetSocketAddress(lastProxy);
      }
      lastInetSocketAddress = nextInetSocketAddress();
      resetNextTlsVersion();
    }

    String tlsVersion = nextTlsVersion();
    Route route = new Route(address, lastProxy, lastInetSocketAddress, tlsVersion);
    if (routeDatabase.shouldPostpone(route)) {
      postponedRoutes.add(route);
      // We will only recurse in order to skip previously failed routes. They will be
      // tried last.
      return nextUnconnected();
    }

    return new Connection(pool, route);
  }
  protected String get(String url) throws IOException, ApiException, JSONException {

    String responseString = "";

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder().url(url).build();

    Response response = client.newCall(request).execute();
    responseString = response.body().string();

    if (!response.isSuccessful()) {
      handleError(response.code(), request.uri() + "", responseString);
    }

    return responseString;
  }
Example #25
0
 public Response proceed(Request request1)
 {
     calls = calls + 1;
     if (index > 0)
     {
         Interceptor interceptor = (Interceptor)client.networkInterceptors().get(index - 1);
         Address address1 = connection().getRoute().getAddress();
         if (!request1.httpUrl().host().equals(address1.getUriHost()) || request1.httpUrl().port() != address1.getUriPort())
         {
             throw new IllegalStateException((new StringBuilder()).append("network interceptor ").append(interceptor).append(" must retain the same host and port").toString());
         }
         if (calls > 1)
         {
             throw new IllegalStateException((new StringBuilder()).append("network interceptor ").append(interceptor).append(" must call proceed() exactly once").toString());
         }
     }
     if (index >= client.networkInterceptors().size()) goto _L2; else goto _L1
Example #26
0
 private static Address createAddress(OkHttpClient okhttpclient, Request request)
 {
     com.squareup.okhttp.CertificatePinner certificatepinner = null;
     javax.net.ssl.SSLSocketFactory sslsocketfactory;
     javax.net.ssl.HostnameVerifier hostnameverifier;
     if (request.isHttps())
     {
         sslsocketfactory = okhttpclient.getSslSocketFactory();
         hostnameverifier = okhttpclient.getHostnameVerifier();
         certificatepinner = okhttpclient.getCertificatePinner();
     } else
     {
         hostnameverifier = null;
         sslsocketfactory = null;
     }
     return new Address(request.httpUrl().host(), request.httpUrl().port(), okhttpclient.getSocketFactory(), sslsocketfactory, hostnameverifier, certificatepinner, okhttpclient.getAuthenticator(), okhttpclient.getProxy(), okhttpclient.getProtocols(), okhttpclient.getConnectionSpecs(), okhttpclient.getProxySelector());
 }
Example #27
0
 private Request networkRequest(Request request)
 {
     com.squareup.okhttp.Request.Builder builder = request.newBuilder();
     if (request.header("Host") == null)
     {
         builder.header("Host", Util.hostHeader(request.httpUrl()));
     }
     if ((connection == null || connection.getProtocol() != Protocol.HTTP_1_0) && request.header("Connection") == null)
     {
         builder.header("Connection", "Keep-Alive");
     }
     if (request.header("Accept-Encoding") == null)
     {
         transparentGzip = true;
         builder.header("Accept-Encoding", "gzip");
     }
     CookieHandler cookiehandler = client.getCookieHandler();
     if (cookiehandler != null)
     {
         java.util.Map map = OkHeaders.toMultimap(builder.build().headers(), null);
         OkHeaders.addCookies(builder, cookiehandler.get(request.uri(), map));
     }
     if (request.header("User-Agent") == null)
     {
         builder.header("User-Agent", Version.userAgent());
     }
     return builder.build();
 }
 /**
  * Prepares the HTTP headers and sends them to the server.
  *
  * <p>For streaming requests with a body, headers must be prepared <strong>before</strong> the
  * output stream has been written to. Otherwise the body would need to be buffered!
  *
  * <p>For non-streaming requests with a body, headers must be prepared <strong>after</strong> the
  * output stream has been written to and closed. This ensures that the {@code Content-Length}
  * header field receives the proper value.
  */
 public void writeRequestHeaders(Request request) throws IOException {
   httpEngine.writingRequestHeaders();
   String requestLine =
       RequestLine.get(
           request,
           httpEngine.getConnection().getRoute().getProxy().type(),
           httpEngine.getConnection().getProtocol());
   httpConnection.writeRequest(request.headers(), requestLine);
 }
 @Override
 public Response intercept(Chain chain) throws IOException {
   Request request = chain.request();
   Optional<String> appAuthHeader = Optional.fromNullable(request.header(X_API_KEY_HEADER));
   if (appAuthHeader.isPresent()) {
     final Request.Builder newRequest = request.newBuilder();
     final String today = getTodayDate();
     newRequest.addHeader(DATE_HEADER, today);
     Signature signature =
         getSigner()
             .sign(
                 request.method(),
                 request.urlString(),
                 Collections.singletonMap(DATE_HEADER, today));
     newRequest.addHeader(AUTHORIZATION_HEADER, signature.toString());
     request = newRequest.build();
   }
   return chain.proceed(request);
 }
  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Logger.v(
        String.format(
            "Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Logger.v(
        String.format(
            "Received response for %s in %.1fms%n%s",
            response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }