Esempio n. 1
1
  protected String doInBackground(ArrayList<String>... args) {
    ArrayList<String> l = args[0];

    String value = l.get(1);
    String fileName = l.get(0);
    System.out.println(value);
    System.out.println(fileName);
    try {

      OkHttpClient client = new OkHttpClient();
      RequestBody formBody =
          new FormBody.Builder().add("texte", value).add("fichier", fileName).build();
      Request request =
          new Request.Builder()
              .url("http://theprintmint-framing.com/tp2/writefile.php")
              .post(formBody)
              .build();

      Response response = client.newCall(request).execute();
      if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

      System.out.println(response.body().string());

    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
  public ServerInfoJson getServerInfo(HttpUrl serverUrl, String serverID, String id)
      throws IOException {
    // set timeout to 30 seconds
    OkHttpClient client =
        defaultClient
            .newBuilder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("version", 1);
    jsonObject.addProperty("command", "get_server_info");
    jsonObject.addProperty("stop_when_error", "false");
    jsonObject.addProperty("stop_when_success", "false");
    jsonObject.addProperty("id", id);
    jsonObject.addProperty("serverID", serverID);
    RequestBody requestBody =
        RequestBody.create(MediaType.parse("text/plain"), gson.toJson(jsonObject));
    Request request = new Request.Builder().url(serverUrl).post(requestBody).build();
    Response response = client.newCall(request).execute();
    InputStream in = response.body().byteStream();
    JsonReader reader = null;
    ServerInfoJson serverInfoJson = null;
    try {
      reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
      serverInfoJson = gson.fromJson(reader, ServerInfoJson.class);
    } finally {
      if (reader != null) {
        reader.close();
      }
    }

    if (serverInfoJson != null) {
      if (serverInfoJson.server != null) {
        // server info found!
        return serverInfoJson;
      } else if (serverInfoJson.sites != null && !serverInfoJson.sites.isEmpty()) {
        String site = serverInfoJson.sites.get(0);
        return getServerInfo(
            new HttpUrl.Builder().scheme("http").host(site).addPathSegment("Serv.php").build(),
            serverID,
            id);
      }
    }

    throw new IOException("No server info found!");
  }
Esempio n. 3
0
  @Test
  public void proxySelector() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));

    ProxySelector proxySelector =
        new ProxySelector() {
          @Override
          public List<Proxy> select(URI uri) {
            return Collections.singletonList(socksProxy.proxy());
          }

          @Override
          public void connectFailed(URI uri, SocketAddress socketAddress, IOException e) {
            throw new AssertionError();
          }
        };

    OkHttpClient client = new OkHttpClient.Builder().setProxySelector(proxySelector).build();

    Request request = new Request.Builder().url(server.url("/")).build();
    Response response = client.newCall(request).execute();
    assertEquals("abc", response.body().string());

    assertEquals(1, socksProxy.connectionCount());
  }
  private String authorize() {
    try {
      OkHttpClient.Builder builder = client.newBuilder();
      builder.interceptors().remove(this);
      OkHttpClient clone = builder.build();

      String credential = Credentials.basic(config.getUsername(), new String(config.getPassword()));
      URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH));
      Response response =
          clone
              .newCall(
                  new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build())
              .execute();

      response.body().close();
      response = response.priorResponse() != null ? response.priorResponse() : response;
      response = response.networkResponse() != null ? response.networkResponse() : response;
      String token = response.header(LOCATION);
      if (token == null || token.isEmpty()) {
        throw new KubernetesClientException(
            "Unexpected response ("
                + response.code()
                + " "
                + response.message()
                + "), to the authorization request. Missing header:["
                + LOCATION
                + "]!");
      }
      token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length());
      token = token.substring(0, token.indexOf(AFTER_TOKEN));
      return token;
    } catch (Exception e) {
      throw KubernetesClientException.launderThrowable(e);
    }
  }
Esempio n. 5
0
  public static int UserMatch() throws IOException, JSONException {
    if (android.os.Build.VERSION.SDK_INT > 9) {

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

      StrictMode.setThreadPolicy(policy);
    }

    OkHttpClient client = new OkHttpClient();

    RequestBody formBody =
        new FormBody.Builder().add("username", username).add("password", password).build();
    Request request =
        new Request.Builder()
            .url("http://projetdeweb.azurewebsites.net/API/Connection/Connect")
            .post(formBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());

    int Rights = -1;
    JSONArray jsonArray = new JSONArray(response.body().string());
    for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject jsonObject = jsonArray.getJSONObject(i);
      Rights = jsonObject.optInt("Rights");
    }

    return Rights;
  }
Esempio n. 6
0
  public void execute(String url, final IRespListener listener) {
    RequestBody reqBody = builder.build();
    Request req = new Request.Builder().url(url).post(reqBody).build();
    OkHttpClient http = new OkHttpClient();
    http.newCall(req)
        .enqueue(
            new Callback() {
              @Override
              public void onFailure(final Call call, final IOException e) {
                Log.d("szw", "http error : " + e);
                handler.post(
                    new Runnable() {
                      @Override
                      public void run() {
                        listener.onHttpFail(call, e);
                      }
                    });
              }

              @Override
              public void onResponse(final Call call, final Response response) throws IOException {
                handler.post(
                    new Runnable() {
                      @Override
                      public void run() {
                        try {
                          listener.onHttpResp(call, response.body().string());
                        } catch (IOException e) {
                          e.printStackTrace();
                        }
                      }
                    });
              }
            });
  }
Esempio n. 7
0
  public HttpCodec newStream(OkHttpClient client, boolean doExtensiveHealthChecks) {
    int connectTimeout = client.connectTimeoutMillis();
    int readTimeout = client.readTimeoutMillis();
    int writeTimeout = client.writeTimeoutMillis();
    boolean connectionRetryEnabled = client.retryOnConnectionFailure();

    try {
      RealConnection resultConnection =
          findHealthyConnection(
              connectTimeout,
              readTimeout,
              writeTimeout,
              connectionRetryEnabled,
              doExtensiveHealthChecks);

      HttpCodec resultCodec;
      if (resultConnection.http2Connection != null) {
        resultCodec = new Http2Codec(client, this, resultConnection.http2Connection);
      } else {
        resultConnection.socket().setSoTimeout(readTimeout);
        resultConnection.source.timeout().timeout(readTimeout, MILLISECONDS);
        resultConnection.sink.timeout().timeout(writeTimeout, MILLISECONDS);
        resultCodec = new Http1Codec(client, this, resultConnection.source, resultConnection.sink);
      }

      synchronized (connectionPool) {
        codec = resultCodec;
        return resultCodec;
      }
    } catch (IOException e) {
      throw new RouteException(e);
    }
  }
Esempio n. 8
0
 /** Sets the response cache to be used to read and write cached responses. */
 public static void setResponseCache(OkUrlFactory okUrlFactory, ResponseCache responseCache) {
   OkHttpClient client = okUrlFactory.client();
   if (responseCache instanceof OkCacheContainer) {
     // Avoid adding layers of wrappers. Rather than wrap the ResponseCache in yet another layer to
     // make the ResponseCache look like an InternalCache, we can unwrap the Cache instead.
     // This means that Cache stats will be correctly updated.
     OkCacheContainer okCacheContainer = (OkCacheContainer) responseCache;
     client.setCache(okCacheContainer.getCache());
   } else {
     client.setInternalCache(responseCache != null ? new CacheAdapter(responseCache) : null);
   }
 }
Esempio n. 9
0
 @Override
 public Response execute() throws IOException {
   synchronized (this) {
     if (executed) throw new IllegalStateException("Already Executed");
     executed = true;
   }
   try {
     client.dispatcher().executed(this);
     Response result = getResponseWithInterceptorChain();
     if (result == null) throw new IOException("Canceled");
     return result;
   } finally {
     client.dispatcher().finished(this);
   }
 }
Esempio n. 10
0
  @Test
  public void checkRemoteDNSResolve() throws Exception {
    // This testcase will fail if the target is resolved locally instead of through the proxy.
    server.enqueue(new MockResponse().setBody("abc"));

    OkHttpClient client = new OkHttpClient.Builder().setProxy(socksProxy.proxy()).build();

    HttpUrl url =
        server.url("/").newBuilder().host(socksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS).build();

    Request request = new Request.Builder().url(url).build();
    Response response1 = client.newCall(request).execute();
    assertEquals("abc", response1.body().string());

    assertEquals(1, socksProxy.connectionCount());
  }
Esempio n. 11
0
  /**
   * 将Json转为Bean
   *
   * @param tag
   * @param url
   * @param headers
   * @param beanClass
   * @param getBeanCallBack
   * @param <T>
   */
  public static <T> void getBean(
      Object tag,
      String url,
      Map<String, String> headers,
      final Class<T> beanClass,
      final GetBeanCallBack<T> getBeanCallBack) {
    Logger.i(TAG, "getBean url:" + url);
    setCancel(false);
    if (mClient != null) {
      Request.Builder requestBuilder = new Request.Builder();
      requestBuilder.tag(tag);
      requestBuilder.url(url);
      appendHeaders(requestBuilder, headers);
      Request request = requestBuilder.build();
      mCall = mClient.newCall(request);
      mCalls.add(mCall);
      mCall.enqueue(
          new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              Logger.e(TAG, "getBean onFailure" + e.getMessage());
              EventBus.getDefault().post(new NetWorkBadEvent());
              getBeanCallBack.onFailure(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
              if (response.isSuccessful()) {
                getBeanCallBack.onResponse(GsonUtils.fromJson(response.body().string(), beanClass));
              }
            }
          });
    }
  }
Esempio n. 12
0
  /**
   * base 的 get请求
   *
   * @param tag
   * @param url
   * @param headers
   * @param getCallBack
   */
  public static void get(
      Object tag, String url, Map<String, String> headers, final GetCallBack getCallBack) {
    Logger.i(TAG, "get url :" + url);
    setCancel(false);
    if (mClient != null) {
      Request.Builder requestBuilder = new Request.Builder();
      requestBuilder.tag(tag);
      requestBuilder.url(url);
      appendHeaders(requestBuilder, headers);
      Request request = requestBuilder.build();
      mCall = mClient.newCall(request);
      mCalls.add(mCall);
      mCall.enqueue(
          new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              getCallBack.onFailure(call, e);
              Logger.e(TAG, "get onFailure:" + e.getMessage());
              EventBus.getDefault().post(new NetWorkBadEvent());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
              if (response.isSuccessful()) {
                getCallBack.onResponse(call, response);
              } else {
                getCallBack.onError(response.toString());
              }
            }
          });
    }
  }
Esempio n. 13
0
 private static OkHttpClient client() {
   return client
       .newBuilder()
       .connectTimeout(250, TimeUnit.MILLISECONDS)
       .readTimeout(250, TimeUnit.MILLISECONDS)
       .build();
 }
  public FootballDataAPI(Context context) {
    mContext = context;

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    // set your desired log level
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);

    mHttpClient =
        new OkHttpClient.Builder()
            .addInterceptor(new HeaderInterceptor())
            .addInterceptor(new ApiLimitInterceptor())
            .addInterceptor(logging)
            .build();

    // limit the number of concurrent async calls
    mHttpClient.dispatcher().setMaxRequests(5);

    Retrofit retrofit =
        new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(mHttpClient)
            .build();

    mApiService = retrofit.create(FootballDataService.class);
  }
Esempio n. 15
0
  public CacheResponse(File cacheDirectory) throws Exception {
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    Cache cache = new Cache(cacheDirectory, cacheSize);

    client = new OkHttpClient();
    client.setCache(cache);
  }
Esempio n. 16
0
  @Test
  public void testNetscapeResponse() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));
    MockWebServer server = new MockWebServer();
    server.start();

    HttpUrl urlWithIpAddress = urlWithIpAddress(server, "/path/foo");
    server.enqueue(
        new MockResponse()
            .addHeader(
                "Set-Cookie: a=android; "
                    + "expires=Fri, 31-Dec-9999 23:59:59 GMT; "
                    + "path=/path; "
                    + "domain="
                    + urlWithIpAddress.host()
                    + "; "
                    + "secure"));
    get(urlWithIpAddress);

    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals(null, cookie.getComment());
    assertEquals(null, cookie.getCommentURL());
    assertEquals(false, cookie.getDiscard());
    assertTrue(cookie.getMaxAge() > 100000000000L);
    assertEquals("/path", cookie.getPath());
    assertEquals(true, cookie.getSecure());
    assertEquals(0, cookie.getVersion());
  }
Esempio n. 17
0
  public Request testSSL(Context context, final OnResultListener<String> listener) {
    Request request = new Request.Builder().url("https://192.168.210.51:8443/test.html").build();
    final CallbackObject<String> callbackObject = new CallbackObject<String>();

    callbackObject.request = request;
    callbackObject.listener = listener;
    mClient
        .newCall(request)
        .enqueue(
            new Callback() {
              @Override
              public void onFailure(Call call, IOException e) {
                callbackObject.exception = e;
                Message msg = mHandler.obtainMessage(MESSAGE_FAILURE, callbackObject);
                mHandler.sendMessage(msg);
              }

              @Override
              public void onResponse(Call call, Response response) throws IOException {
                callbackObject.result = response.body().string();
                Message msg = mHandler.obtainMessage(MESSAGE_SUCCESS, callbackObject);
                mHandler.sendMessage(msg);
              }
            });

    return request;
  }
Esempio n. 18
0
  @Test
  public void testRfc2109Response() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));
    MockWebServer server = new MockWebServer();
    server.start();

    HttpUrl urlWithIpAddress = urlWithIpAddress(server, "/path/foo");
    server.enqueue(
        new MockResponse()
            .addHeader(
                "Set-Cookie: a=android; "
                    + "Comment=this cookie is delicious; "
                    + "Domain="
                    + urlWithIpAddress.host()
                    + "; "
                    + "Max-Age=60; "
                    + "Path=/path; "
                    + "Secure; "
                    + "Version=1"));
    get(urlWithIpAddress);

    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals(null, cookie.getCommentURL());
    assertEquals(false, cookie.getDiscard());
    assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding!
    assertEquals("/path", cookie.getPath());
    assertEquals(true, cookie.getSecure());
  }
Esempio n. 19
0
  @Test
  public void testRedirectsDoNotIncludeTooManyCookies() throws Exception {
    MockWebServer redirectTarget = new MockWebServer();
    redirectTarget.enqueue(new MockResponse().setBody("A"));
    redirectTarget.start();

    MockWebServer redirectSource = new MockWebServer();
    redirectSource.enqueue(
        new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
            .addHeader("Location: " + redirectTarget.url("/")));
    redirectSource.start();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookie = new HttpCookie("c", "cookie");
    cookie.setDomain(redirectSource.getHostName());
    cookie.setPath("/");
    String portList = Integer.toString(redirectSource.getPort());
    cookie.setPortlist(portList);
    cookieManager.getCookieStore().add(redirectSource.url("/").uri(), cookie);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));

    get(redirectSource.url("/"));
    RecordedRequest request = redirectSource.takeRequest();

    assertEquals("c=cookie", request.getHeader("Cookie"));

    for (String header : redirectTarget.takeRequest().getHeaders().names()) {
      if (header.startsWith("Cookie")) {
        fail(header);
      }
    }
  }
Esempio n. 20
0
  @Test
  public void testCookiesSentIgnoresCase() throws Exception {
    client.setCookieJar(
        new JavaNetCookieJar(
            new CookieManager() {
              @Override
              public Map<String, List<String>> get(
                  URI uri, Map<String, List<String>> requestHeaders) throws IOException {
                Map<String, List<String>> result = new HashMap<>();
                result.put("COOKIE", Collections.singletonList("Bar=bar"));
                result.put("cooKIE2", Collections.singletonList("Baz=baz"));
                return result;
              }
            }));

    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.start();

    get(server.url("/"));

    RecordedRequest request = server.takeRequest();
    assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
    assertNull(request.getHeader("Cookie2"));
    assertNull(request.getHeader("Quux"));
  }
Esempio n. 21
0
 @Override
 public void enqueue(Callback responseCallback) {
   synchronized (this) {
     if (executed) throw new IllegalStateException("Already Executed");
     executed = true;
   }
   client.dispatcher().enqueue(new AsyncCall(responseCallback));
 }
Esempio n. 22
0
  private Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!retryAndFollowUpInterceptor.isForWebSocket()) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(retryAndFollowUpInterceptor.isForWebSocket()));

    Interceptor.Chain chain =
        new RealInterceptorChain(interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
  }
  protected JSONObject doInBackground(String... strings) {
    JSONObject jsonObject = null;

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(URL_JSON).build();

    Response response;
    try {
      response = client.newCall(request).execute();
      if (!response.isSuccessful()) throw new IOException(String.valueOf(response));

      jsonObject = new JSONObject(response.body().string());
    } catch (IOException | JSONException e) {
      e.printStackTrace();
    }
    return jsonObject;
  }
Esempio n. 24
0
 public static byte[] postGetByte(String url, String json) throws IOException {
   RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build();
   Request request = new Request.Builder().url(url).post(formBody).build();
   Response response = client.newCall(request).execute();
   if (response.isSuccessful()) {
     return response.body().bytes();
   }
   return null;
 }
Esempio n. 25
0
  @Test
  public void proxy() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.enqueue(new MockResponse().setBody("def"));

    OkHttpClient client = new OkHttpClient.Builder().setProxy(socksProxy.proxy()).build();

    Request request1 = new Request.Builder().url(server.url("/")).build();
    Response response1 = client.newCall(request1).execute();
    assertEquals("abc", response1.body().string());

    Request request2 = new Request.Builder().url(server.url("/")).build();
    Response response2 = client.newCall(request2).execute();
    assertEquals("def", response2.body().string());

    // The HTTP calls should share a single connection.
    assertEquals(1, socksProxy.connectionCount());
  }
Esempio n. 26
0
 public void run() {
   OkHttpClient client = new OkHttpClient();
   System.out.println("[PARAMS] : " + _token + " login -> " + _login);
   HttpUrl url =
       new HttpUrl.Builder()
           .scheme("https")
           .host("epitech-api.herokuapp.com")
           .addPathSegment("user")
           .addQueryParameter("token", _token)
           .addQueryParameter("user", _login)
           .build();
   Request request = new Request.Builder().url(url).get().build();
   try {
     infos = client.newCall(request).execute().body().string();
     System.out.println("[RUN] : " + infos);
   } catch (IOException e) {
     e.printStackTrace();
   }
   return;
 }
Esempio n. 27
0
 /**
  * 同步POST
  *
  * @param url 请求的url
  * @param params 参数
  * @return
  */
 public static String synRequestServerByPost(final String url, JSONObject params) {
   throwException();
   Request request = requestFactory(url, params, true);
   try {
     Response response = mOkHttpClient.newCall(request).execute();
     return response.body().string();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return "";
 }
  public ServerInfoJson requestTunnel(ServerInfoJson infoJson, String serverID, String id)
      throws IOException {
    if (infoJson == null || infoJson.env == null || Util.isEmpty(infoJson.env.control_host)) {
      return null;
    }

    // set timeout to 30 seconds
    OkHttpClient client =
        defaultClient
            .newBuilder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    final String server = infoJson.env.control_host;

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("command", "request_tunnel");
    jsonObject.addProperty("version", 1);
    jsonObject.addProperty("serverID", serverID);
    jsonObject.addProperty("id", id);

    RequestBody requestBody =
        RequestBody.create(MediaType.parse("text/plain"), gson.toJson(jsonObject));
    Request request =
        new Request.Builder()
            .url(HttpUrl.parse("http://" + server + "/Serv.php"))
            .post(requestBody)
            .build();
    Response response = client.newCall(request).execute();
    JsonReader reader = null;
    try {
      InputStream in = response.body().byteStream();
      reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
      return gson.fromJson(reader, ServerInfoJson.class);
    } finally {
      if (reader != null) {
        reader.close();
      }
    }
  }
    @Override
    public byte[] download(String url, String accepts) {
      HttpUrl httpUrl = HttpUrl.parse(url);

      if (httpUrl == null) {
        App.log.log(Level.SEVERE, "Invalid external resource URL", url);
        return null;
      }

      String host = httpUrl.host();
      if (host == null) {
        App.log.log(Level.SEVERE, "External resource URL doesn't specify a host name", url);
        return null;
      }

      OkHttpClient resourceClient = HttpClient.create();

      // authenticate only against a certain host, and only upon request
      resourceClient =
          HttpClient.addAuthentication(
              resourceClient, baseUrl.host(), settings.username(), settings.password());

      // allow redirects
      resourceClient = resourceClient.newBuilder().followRedirects(true).build();

      try {
        Response response =
            resourceClient.newCall(new Request.Builder().get().url(httpUrl).build()).execute();

        ResponseBody body = response.body();
        if (body != null) {
          @Cleanup InputStream stream = body.byteStream();
          if (response.isSuccessful() && stream != null) {
            return IOUtils.toByteArray(stream);
          } else App.log.severe("Couldn't download external resource");
        }
      } catch (IOException e) {
        App.log.log(Level.SEVERE, "Couldn't download external resource", e);
      }
      return null;
    }
Esempio n. 30
0
  private InputStream prepareConnection() throws IOException {
    Request request = new Request.Builder().url(url).build();

    Response response = CLIENT.newCall(request).execute();

    if (response.code() != 200) {
      Log.e("ERROR", "Server returned HTTP " + response.message());
      return null;
    }

    return response.body().byteStream();
  }