Exemple #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!");
  }
Exemple #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());
  }
  @Override
  public Response intercept(Chain chain) throws IOException {

    Request request = chain.request();

    long t1 = System.nanoTime();
    L.i(
        TAG,
        "Sending request="
            + request.url()
            + "   connection="
            + chain.connection()
            + "    head="
            + request.headers()
            + " request=");

    Response response = chain.proceed(request);
    long t2 = System.nanoTime();
    L.i(
        TAG,
        "Received response="
            + response.request().url()
            + "   connect time="
            + ((t2 - t1) / 1e6d)
            + "    head="
            + response.headers()
            + "    tostring"
            + response.toString());

    return response;
  }
Exemple #5
0
 @Test
 public void parseNameValueBlock() throws IOException {
   List<Header> headerBlock =
       headerEntries(
           "cache-control", "no-cache, no-store",
           "set-cookie", "Cookie1\u0000Cookie2",
           ":status", "200 OK",
           ":version", "HTTP/1.1");
   Request request = new Request.Builder().url("http://square.com/").build();
   Response response = Http2xStream.readSpdy3HeadersList(headerBlock).request(request).build();
   Headers headers = response.headers();
   assertEquals(3, headers.size());
   Assert.assertEquals(Protocol.SPDY_3, response.protocol());
   assertEquals(200, response.code());
   assertEquals("OK", response.message());
   assertEquals("no-cache, no-store", headers.get("cache-control"));
   assertEquals("Cookie2", headers.get("set-cookie"));
   assertEquals("cache-control", headers.name(0));
   assertEquals("no-cache, no-store", headers.value(0));
   assertEquals("set-cookie", headers.name(1));
   assertEquals("Cookie1", headers.value(1));
   assertEquals("set-cookie", headers.name(2));
   assertEquals("Cookie2", headers.value(2));
   assertNull(headers.get(":status"));
   assertNull(headers.get(":version"));
 }
Exemple #6
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;
  }
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
      Request request = chain.request();
      Response response = null;
      boolean responseOK = false;
      int tryCount = 0;

      while (!responseOK && tryCount < MAX_RETRY) {
        try {
          response = chain.proceed(request);
          int statusCode = response.code();
          if (statusCode == 200) {
            responseOK = response.isSuccessful();
          } else {
            // rate is limited by the number of calls per min
            Thread.sleep(API_LIMIT_INTERVAL);
          }
        } catch (Exception e) {
          Log.d(LOG_TAG, "Request is not successful - " + tryCount);
        } finally {
          tryCount++;
        }
      }
      // otherwise just pass the original response on
      return response;
    }
Exemple #8
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;
 }
  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);
    }
  }
 @Test
 public void interceptorDoesAddUserAgent() throws Exception {
   Request request = new Request.Builder().url("https://test.desk.com").build();
   assertFalse(doesHaveUserAgent(request));
   OkHttpClient.Builder builder = new OkHttpClient.Builder();
   builder.interceptors().add(userAgentInterceptor);
   Call call = builder.build().newCall(request);
   Response response = call.execute();
   assertTrue(doesHaveUserAgent(response.request()));
   assertEquals(TEST_USER_AGENT, response.request().header(HEADER_USER_AGENT));
 }
 /**
  * 同步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 "";
 }
  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();
  }
Exemple #13
0
 @Test
 public void readNameValueBlockDropsForbiddenHeadersSpdy3() throws IOException {
   List<Header> headerBlock =
       headerEntries(
           ":status", "200 OK",
           ":version", "HTTP/1.1",
           "connection", "close");
   Request request = new Request.Builder().url("http://square.com/").build();
   Response response = Http2xStream.readSpdy3HeadersList(headerBlock).request(request).build();
   Headers headers = response.headers();
   assertEquals(0, headers.size());
 }
 @Override
 protected String doInBackground(Void... voids) {
   Request request = new Request.Builder().url(SERVER_ADDRESS).get().build();
   try {
     Response response = MainActivity.this.httpClient.newCall(request).execute();
     String result = response.body().string();
     return result;
   } catch (IOException e) {
     e.printStackTrace();
   }
   return null;
 }
  @Override
  public long open(DataSpec dataSpec) throws HttpDataSourceException {
    this.dataSpec = dataSpec;
    this.bytesRead = 0;
    this.bytesSkipped = 0;
    Request request = makeRequest(dataSpec);
    try {
      response = okHttpClient.newCall(request).execute();
      responseByteStream = response.body().byteStream();
    } catch (IOException e) {
      throw new HttpDataSourceException(
          "Unable to connect to " + dataSpec.uri.toString(), e, dataSpec);
    }

    int responseCode = response.code();

    // Check for a valid response code.
    if (!response.isSuccessful()) {
      Map<String, List<String>> headers = request.headers().toMultimap();
      closeConnectionQuietly();
      throw new InvalidResponseCodeException(responseCode, headers, dataSpec);
    }

    // Check for a valid content type.
    MediaType mediaType = response.body().contentType();
    String contentType = mediaType != null ? mediaType.toString() : null;
    if (contentTypePredicate != null && !contentTypePredicate.evaluate(contentType)) {
      closeConnectionQuietly();
      throw new InvalidContentTypeException(contentType, dataSpec);
    }

    // If we requested a range starting from a non-zero position and received a 200 rather than a
    // 206, then the server does not support partial requests. We'll need to manually skip to the
    // requested position.
    bytesToSkip = responseCode == 200 && dataSpec.position != 0 ? dataSpec.position : 0;

    // Determine the length of the data to be read, after skipping.
    long contentLength = response.body().contentLength();
    bytesToRead =
        dataSpec.length != C.LENGTH_UNBOUNDED
            ? dataSpec.length
            : contentLength != -1 ? contentLength - bytesToSkip : C.LENGTH_UNBOUNDED;

    opened = true;
    if (listener != null) {
      listener.onTransferStart();
    }

    return bytesToRead;
  }
  public void run() throws Exception {
    Request request =
        new Request.Builder().url("https://api.github.com/gists/c2a7c39532239ff261be").build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    Gist gist = gistJsonAdapter.fromJson(response.body().source());
    response.body().close();

    for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
      System.out.println(entry.getKey());
      System.out.println(entry.getValue().content);
    }
  }
Exemple #17
0
  public void run() throws Exception {
    File file = new File("README.md");

    Request request =
        new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
            .build();

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

    System.out.println(response.body().string());
  }
  public File saveFile(Response response) throws IOException {
    InputStream is = null;
    byte[] buf = new byte[2048];
    int len = 0;
    FileOutputStream fos = null;
    try {
      is = response.body().byteStream();
      final long total = response.body().contentLength();
      long sum = 0;

      L.e(total + "");

      File dir = new File(destFileDir);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      File file = new File(dir, destFileName);
      fos = new FileOutputStream(file);
      while ((len = is.read(buf)) != -1) {
        sum += len;
        fos.write(buf, 0, len);
        final long finalSum = sum;
        OkHttpUtils.getInstance()
            .getDelivery()
            .post(
                new Runnable() {
                  @Override
                  public void run() {

                    inProgress(finalSum, total);
                  }
                });
      }
      fos.flush();

      return file;

    } finally {
      try {
        if (is != null) is.close();
      } catch (IOException e) {
      }
      try {
        if (fos != null) fos.close();
      } catch (IOException e) {
      }
    }
  }
  @Override
  public synchronized Request authenticate(Route route, final Response response)
      throws IOException {
    logger.warn(response.toString());

    final AuthResponse currentAuth = loginPrefs.getCurrentAuth();
    if (null == currentAuth || null == currentAuth.refresh_token) {
      return null;
    }

    String errorCode = getErrorCode(response.peekBody(200).string());

    if (errorCode != null) {
      switch (errorCode) {
        case TOKEN_EXPIRED_ERROR_MESSAGE:
          final AuthResponse refreshedAuth;
          try {
            refreshedAuth = refreshAccessToken(currentAuth);
          } catch (HttpResponseStatusException e) {
            return null;
          }
          return response
              .request()
              .newBuilder()
              .header("Authorization", refreshedAuth.token_type + " " + refreshedAuth.access_token)
              .build();
        case TOKEN_NONEXISTENT_ERROR_MESSAGE:
        case TOKEN_INVALID_GRANT_ERROR_MESSAGE:
          // Retry request with the current access_token if the original access_token used in
          // request does not match the current access_token. This case can occur when
          // asynchronous calls are made and are attempting to refresh the access_token where
          // one call succeeds but the other fails. https://github.com/edx/edx-app-android/pull/834
          if (!response
              .request()
              .headers()
              .get("Authorization")
              .split(" ")[1]
              .equals(currentAuth.access_token)) {
            return response
                .request()
                .newBuilder()
                .header("Authorization", currentAuth.token_type + " " + currentAuth.access_token)
                .build();
          }
      }
    }
    return null;
  }
Exemple #20
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());
  }
 @Override
 public AskForLeaveEntity parseNetworkResponse(Response response) throws Exception {
   String s = response.body().string();
   if (TextUtils.isEmpty(s)) {
     return null;
   }
   return JsonUtils.getPerson(s, AskForLeaveEntity.class);
 }
  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;
  }
  /**
   * post JSON data to server
   *
   * @param url
   * @param json
   * @param callBack
   */
  public void post(String url, String json, final HttpCallBack callBack) {

    RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = null;
    try {
      response = mOkHttpClient.newCall(request).execute();
      if (response.isSuccessful()) {
        callBack.onSuccess(response.body().string());
      } else {
        callBack.onError(new Exception("Unexpected code " + response));
      }
    } catch (IOException e) {
      e.printStackTrace();
      callBack.onError(e);
    }
  }
  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    // Build new request
    Request.Builder builder = request.newBuilder();
    builder.header("Accept", "application/json");

    String token = oauthToken.get();
    if (Utils.isNotNullOrEmpty(token)) {
      setAuthHeader(builder, token);
    }

    request = builder.build();
    Response response = chain.proceed(request);

    // If response is Forbidden or Unauthorized, try to obtain a token via authorize() or via
    // config.
    if (response.code() != 401 && response.code() != 403) {
      return response;
    } else if (Utils.isNotNullOrEmpty(config.getUsername())
        && Utils.isNotNullOrEmpty(config.getPassword())) {
      synchronized (client) {
        token = authorize();
        if (token != null) {
          oauthToken.set(token);
        }
      }
    } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
      token = config.getOauthToken();
      oauthToken.set(token);
    }

    // If token was obtain, then retry request using the obtained token.
    if (Utils.isNotNullOrEmpty(token)) {
      // Close the previous response to prevent leaked connections.
      response.body().close();

      setAuthHeader(builder, token);
      request = builder.build();
      return chain.proceed(request); // repeat request with new token
    } else {
      return response;
    }
  }
 @Override
 public Map<String, Object> parseNetworkResponse(Response response) throws Exception {
   String string = response.body().string();
   System.out.println(string);
   Map<String, Object> resultMap =
       AppApplication.getSingleGson()
           .fromJson(string, new TypeToken<Map<String, Object>>() {}.getType());
   return resultMap;
 }
Exemple #26
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());
  }
Exemple #27
0
 public String get(String url) {
   Request request = null;
   Response response = null;
   try {
     request = new Request.Builder().url(url).build();
     response = client.newCall(request).execute();
     if (response.isSuccessful()) {
       return response.body().string();
     }
     return null;
   } catch (Exception e) {
     System.err.println(e);
   } finally {
     if (response != null && response.body() != null) {
       response.body().close();
     }
   }
   return null;
 }
 public static <R> R parseJson(okhttp3.Response response, Type bodyType)
     throws HasuraJsonException {
   int code = response.code();
   try {
     String rawBody = response.body().string();
     System.out.println(rawBody);
     return gson.fromJson(rawBody, bodyType);
   } catch (JsonSyntaxException e) {
     String msg =
         "FATAL : JSON strucutre not as expected. Schema changed maybe? : " + e.getMessage();
     throw new HasuraJsonException(code, msg, e);
   } catch (JsonParseException e) {
     String msg = "FATAL : Server didn't return vaild JSON : " + e.getMessage();
     throw new HasuraJsonException(code, msg, e);
   } catch (IOException e) {
     String msg = "FATAL : Decoding response body failed : " + e.getMessage();
     throw new HasuraJsonException(code, msg, e);
   }
 }
  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;
    }