Exemplo 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;
  }
    @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;
    }
Exemplo n.º 3
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;
  }
Exemplo n.º 4
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;
 }
Exemplo n.º 5
0
  public void run() throws Exception {
    Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();

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

    String response1Body = response1.body().string();
    System.out.println("Response 1 response:          " + response1);
    System.out.println("Response 1 cache response:    " + response1.cacheResponse());
    System.out.println("Response 1 network response:  " + response1.networkResponse());

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

    String response2Body = response2.body().string();
    System.out.println("Response 2 response:          " + response2);
    System.out.println("Response 2 cache response:    " + response2.cacheResponse());
    System.out.println("Response 2 network response:  " + response2.networkResponse());

    System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));
  }
Exemplo n.º 6
0
  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);
    }
  }
  @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;
  }
Exemplo n.º 8
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());
  }
  /**
   * 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);
    }
  }
  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;
  }
Exemplo n.º 11
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;
 }
Exemplo n.º 12
0
    @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;
    }
Exemplo n.º 13
0
    @Override
    public void run() {
      try {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(SO_URL).build();
        Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
          Reader in = response.body().charStream();
          BufferedReader reader = new BufferedReader(in);

          rawResult = new Gson().fromJson(reader, SOQuestions.class);
          reader.close();

          EventBus.getDefault().post(new ThingsLoadedEvent(QuestionsLoader.this));
        } else {
          Log.e(getClass().getSimpleName(), response.toString());
        }
      } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
      }
    }
Exemplo n.º 14
0
  public void run(String caminho) {
    final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    OkHttpClient client = new OkHttpClient();
    RequestBody requestBody =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file", "imagem.png", RequestBody.create(MEDIA_TYPE_PNG, new File(caminho)))
            .build();

    Request request = new Request.Builder().url(urlfoto).post(requestBody).build();

    Response response = null;
    try {
      response = client.newCall(request).execute();

      if (response.isSuccessful()) {
        livro.setFoto(response.body().string());
        runOnUiThread(
            new Runnable() {
              @Override
              public void run() {
                Picasso.with(AddAnuncioActivity.this)
                    .load(urlfoto + livro.getFoto())
                    .placeholder(R.drawable.ic_menu_camera)
                    .error(R.drawable.ic_menu_camera)
                    .into(addImagemLivro);
              }
            });
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Begin a static scan on FoD
   *
   * @param uploadRequest zip file to upload
   * @return true if the scan succeeded
   */
  @SuppressFBWarnings(
      value = "REC_CATCH_EXCEPTION",
      justification =
          "The intent of the catch-all is to make sure that the Jenkins user and logs show the plugin's problem in the build log.")
  public boolean startStaticScan(final JobConfigModel uploadRequest) {
    PrintStream logger = FodUploaderPlugin.getLogger();

    PostStartScanResponse scanStartedResponse = null;

    File uploadFile = uploadRequest.getUploadFile();
    try (FileInputStream fs = new FileInputStream(uploadFile)) {
      byte[] readByteArray = new byte[CHUNK_SIZE];
      byte[] sendByteArray;
      int fragmentNumber = 0;
      int byteCount;
      long offset = 0;

      if (api.getToken() == null) api.authenticate();

      if (!uploadRequest.hasAssessmentTypeId() && !uploadRequest.hasTechnologyStack()) {
        logger.println("Missing Assessment Type or Technology Stack.");
        return false;
      }

      // Build 'static' portion of url
      String fragUrl =
          api.getBaseUrl()
              + "/api/v3/releases/"
              + uploadRequest.getReleaseId()
              + "/static-scans/start-scan?";
      fragUrl += "assessmentTypeId=" + uploadRequest.getAssessmentTypeId();
      fragUrl += "&technologyStack=" + uploadRequest.getTechnologyStack();
      fragUrl += "&entitlementId=" + uploadRequest.getEntitlementId();
      fragUrl += "&entitlementFrequencyType=" + uploadRequest.getEntitlementFrequencyTypeId();

      if (uploadRequest.hasLanguageLevel())
        fragUrl += "&languageLevel=" + uploadRequest.getLanguageLevel();
      if (uploadRequest.getIsExpressScan()) fragUrl += "&scanPreferenceType=2";
      if (uploadRequest.getIsExpressAudit()) fragUrl += "&auditPreferenceType=2";
      if (uploadRequest.getRunOpenSourceAnalysis())
        fragUrl += "&doSonatypeScan=" + uploadRequest.getRunOpenSourceAnalysis();
      if (uploadRequest.getIsRemediationScan())
        fragUrl += "&isRemediationScan=" + uploadRequest.getIsRemediationScan();
      if (uploadRequest.getExcludeThirdParty())
        fragUrl += "&excludeThirdPartyLibs=" + uploadRequest.getExcludeThirdParty();

      Gson gson = new Gson();

      // Loop through chunks

      logger.println("TOTAL FILE SIZE = " + uploadFile.length());
      logger.println("CHUNK_SIZE = " + CHUNK_SIZE);
      while ((byteCount = fs.read(readByteArray)) != -1) {

        if (byteCount < CHUNK_SIZE) {
          sendByteArray = Arrays.copyOf(readByteArray, byteCount);
          fragmentNumber = -1;
        } else {
          sendByteArray = readByteArray;
        }

        MediaType byteArray = MediaType.parse("application/octet-stream");
        Request request =
            new Request.Builder()
                .addHeader("Authorization", "Bearer " + api.getToken())
                .addHeader("Content-Type", "application/octet-stream")
                // Add offsets
                .url(fragUrl + "&fragNo=" + fragmentNumber++ + "&offset=" + offset)
                .post(RequestBody.create(byteArray, sendByteArray))
                .build();

        // Get the response
        Response response = api.getClient().newCall(request).execute();

        if (response.code()
            == HttpStatus.SC_FORBIDDEN) { // got logged out during polling so log back in
          // Re-authenticate
          api.authenticate();

          // if you had to reauthenticate here, would the loop and request not need to be
          // resubmitted?
          // possible continue?
        }

        offset += byteCount;

        if (fragmentNumber % 5 == 0) {
          logger.println(
              "Upload Status - Fragment No: "
                  + fragmentNumber
                  + ", Bytes sent: "
                  + offset
                  + " (Response: "
                  + response.code()
                  + ")");
        }

        if (response.code() != 202) {
          String responseJsonStr = IOUtils.toString(response.body().byteStream(), "utf-8");

          // final response has 200, try to deserialize it
          if (response.code() == 200) {

            scanStartedResponse = gson.fromJson(responseJsonStr, PostStartScanResponse.class);
            logger.println(
                "Scan "
                    + scanStartedResponse.getScanId()
                    + " uploaded successfully. Total bytes sent: "
                    + offset);
            return true;

          } else if (!response
              .isSuccessful()) { // There was an error along the lines of 'another scan in progress'
                                 // or something

            logger.println("An error occurred during the upload.");
            GenericErrorResponse errors =
                gson.fromJson(responseJsonStr, GenericErrorResponse.class);
            if (errors != null)
              logger.println(
                  "Package upload failed for the following reasons: " + errors.toString());
            return false; // if there is an error, get out of loop and mark build unstable
          }
        }
        response.body().close();
      } // end while
    } catch (Exception e) {
      e.printStackTrace(logger);
      return false;
    }

    return false;
  }