Пример #1
4
  protected String getRallyXML(String apiUrl) throws Exception {
    String responseXML = "";

    DefaultHttpClient httpClient = new DefaultHttpClient();

    Base64 base64 = new Base64();
    String encodeString =
        new String(base64.encode((rallyApiHttpUsername + ":" + rallyApiHttpPassword).getBytes()));

    HttpGet httpGet = new HttpGet(apiUrl);
    httpGet.addHeader("Authorization", "Basic " + encodeString);
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();

    if (entity != null) {

      InputStreamReader reader = new InputStreamReader(entity.getContent());
      BufferedReader br = new BufferedReader(reader);

      StringBuilder sb = new StringBuilder();
      String line = "";
      while ((line = br.readLine()) != null) {
        sb.append(line);
      }

      responseXML = sb.toString();
    }

    log.debug("responseXML=" + responseXML);

    return responseXML;
  }
Пример #2
0
  /**
   * Sends a GET request and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param headers Any additional headers to send with this request. You can use {@link
   *     org.apache.http.HttpHeaders} constants for header names.
   * @return A {@link Path} to the downloaded content, if any.
   * @throws IOException If an error occurs.
   * @see java.nio.file.Files#probeContentType(Path)
   */
  public Response<Path> get(Endpoint endpoint, NameValuePair... headers) throws IOException {

    // Create the request
    HttpGet get = new HttpGet(endpoint.url());
    get.setHeaders(combineHeaders(headers));
    Path tempFile = null;

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(get)) {

      if (response.getStatusLine().getStatusCode() != HttpStatus.OK_200) {
        return null;
      } // If bad response return null

      // Request the content
      HttpEntity entity = response.getEntity();

      // Download the content to a temporary file
      if (entity != null) {
        tempFile = Files.createTempFile("download", "file");
        try (InputStream input = entity.getContent();
            OutputStream output = Files.newOutputStream(tempFile)) {
          IOUtils.copy(input, output);
        }
      }

      return new Response<>(response.getStatusLine(), tempFile);
    }
  }
Пример #3
0
  /**
   * Sends a GET request and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param responseClass The class to deserialise the Json response to. Can be null if no response
   *     message is expected.
   * @param headers Any additional headers to send with this request. You can use {@link
   *     org.apache.http.HttpHeaders} constants for header names.
   * @param <T> The type to deserialise the response to.
   * @return A {@link Response} containing the deserialised body, if any.
   * @throws IOException If an error occurs.
   */
  public <T> Response<T> get(Endpoint endpoint, Class<T> responseClass, NameValuePair... headers)
      throws IOException {

    // Create the request
    HttpGet get = new HttpGet(endpoint.url());
    get.setHeaders(combineHeaders(headers));

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(get)) {
      // System.out.println(response);
      T body = deserialiseResponseMessage(response, responseClass);
      return new Response<>(response.getStatusLine(), body);
    }
  }
Пример #4
0
  public void request1(String uri, int reqNum, int reqTerm) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (reqNum == 0) {
      System.out.println(
          String.format("request to %s infinite times with term '%d' ms", uri, reqTerm));
    } else {
      System.out.println(
          String.format("request to %s '%d' times with term '%d' ms", uri, reqNum, reqTerm));
    }

    int i = 0, tick = 0;
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpResponse response;
    HttpEntity entity;

    while (true) {
      usleep(reqTerm);
      tick = (int) (Math.random() * 10) % 2;
      if (tick == 0) {
        continue;
      }
      System.out.println("request " + httpGet.getURI());
      response = httpclient.execute(httpGet);
      System.out.println("--> response status  = " + response.getStatusLine());
      // response handler
      try {
        entity = response.getEntity();
        EntityUtils.consume(entity);
      } catch (Exception e) {
        System.out.println("  --> http fail:" + e.getMessage());
      } finally {
        // Thread.sleep(5000); //테스트에만 썼다. close 지연시키려고.
        response.close();
      }

      System.out.println("----------------------------------------");
      if (reqNum != 0 && reqNum < ++i) {
        break;
      }
    }
  }
Пример #5
0
  public Either<IOException, HttpResponse> execNormalRequest(
      String path, Map<String, String> params, HTTPMethod method, String acceptType) {
    String url = getUriForPath(path);
    if (params == null) {
      params = new HashMap<String, String>();
    }
    HttpUriRequest httpReq = null;
    if (method.equals(HTTPMethod.GET)) {
      HttpGet get = new HttpGet(url);
      for (Map.Entry<String, String> param : params.entrySet()) {
        get.getParams().setParameter(param.getKey(), param.getValue());
      }
      httpReq = get;
    } else {
      HttpEntityEnclosingRequestBase postOrPut = null;
      if (method.equals(HTTPMethod.PUT)) {
        postOrPut = new HttpPut(url);
      } else {
        postOrPut = new HttpPost(url);
      }
      MultipartEntity entity = new MultipartEntity();

      List<NameValuePair> args = new ArrayList<NameValuePair>();
      for (Map.Entry<String, String> param : params.entrySet()) {
        args.add(new BasicNameValuePair(param.getKey(), param.getValue()));
      }
      try {
        postOrPut.setEntity(new UrlEncodedFormEntity(args));
      } catch (UnsupportedEncodingException e) {
        return new Left<IOException, HttpResponse>(e);
      }
      httpReq = postOrPut;
    }

    return execRequest(httpReq, acceptType);
  }
Пример #6
0
  public void Execute(RequestMethod method) throws Exception {
    switch (method) {
      case GET:
        {
          // add parameters
          String combinedParams = "";
          if (!params.isEmpty()) {
            combinedParams += "?";
            for (NameValuePair p : params) {
              String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8");
              if (combinedParams.length() > 1) {
                combinedParams += "&" + paramString;
              } else {
                combinedParams += paramString;
              }
            }
          }

          HttpGet request = new HttpGet(url + combinedParams);

          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          executeRequest(request, url);
          break;
        }
      case POST:
        {
          HttpPost request = new HttpPost(url);

          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
          }

          executeRequest(request, url);
          break;
        }
      case PUT:
        {
          HttpPut request = new HttpPut(url);

          // add headers
          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
          }

          executeRequest(request, url);
          break;
        }

      case DELETE:
        {
          HttpDelete request = new HttpDelete(url);

          for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
          }

          executeRequest(request, url);
          break;
        }
    }
  }