Java Code Examples for org.apache.commons.httpclient.HttpMethod#getResponseBodyAsString()

The following examples show how to use org.apache.commons.httpclient.HttpMethod#getResponseBodyAsString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GrafanaDashboardServiceImpl.java    From cymbal with Apache License 2.0 6 votes vote down vote up
private void doHttpAPI(HttpMethod method) throws MonitorException {
    // 拼装http post请求,调用grafana http api建立dashboard
    HttpClient httpclient = new HttpClient();
    httpclient.getParams().setConnectionManagerTimeout(Constant.Http.CONN_TIMEOUT);
    httpclient.getParams().setSoTimeout(Constant.Http.SO_TIMEOUT);

    // api key
    method.setRequestHeader("Authorization", String.format("Bearer %s", grafanaApiKey));
    try {

        int statusCode = httpclient.executeMethod(method);
        // 若http请求失败
        if (statusCode != Constant.Http.STATUS_OK) {
            String responseBody = method.getResponseBodyAsString();
            throw new MonitorException(responseBody);
        }
    } catch (Exception e) {
        if (e instanceof MonitorException) {
            throw (MonitorException) e;
        } else {
            new MonitorException(e);
        }
    } finally {
        method.releaseConnection();
    }
}
 
Example 2
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetUser() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/users/" + id1.getKey(), MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final UserVO vo = parse(body, UserVO.class);

    assertNotNull(vo);
    assertEquals(vo.getKey(), id1.getKey());
    assertEquals(vo.getLogin(), id1.getName());
    // are the properties there?
    assertFalse(vo.getProperties().isEmpty());
}
 
Example 3
Source File: SwiftInvalidResponseException.java    From big-c with Apache License 2.0 6 votes vote down vote up
public SwiftInvalidResponseException(String message,
                                     String operation,
                                     URI uri,
                                     HttpMethod method) {
  super(message);
  this.statusCode = method.getStatusCode();
  this.operation = operation;
  this.uri = uri;
  String bodyAsString;
  try {
    bodyAsString = method.getResponseBodyAsString();
    if (bodyAsString == null) {
      bodyAsString = "";
    }
  } catch (IOException e) {
    bodyAsString = "";
  }
  this.body = bodyAsString;
}
 
Example 4
Source File: CoursesITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCourses() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/repo/courses", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<CourseVO> courses = parseCourseArray(body);
    assertNotNull(courses);
    assertTrue(courses.size() >= 2);

    CourseVO vo1 = null;
    CourseVO vo2 = null;
    for (final CourseVO course : courses) {
        if (course.getTitle().equals("courses1")) {
            vo1 = course;
        } else if (course.getTitle().equals("courses2")) {
            vo2 = course;
        }
    }
    assertNotNull(vo1);
    assertEquals(vo1.getKey(), course1.getResourceableId());
    assertNotNull(vo2);
    assertEquals(vo2.getKey(), course2.getResourceableId());
}
 
Example 5
Source File: GroupMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetOwnersAdmin() throws HttpException, IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final String request = "/groups/" + g1.getKey() + "/owners";
    final HttpMethod method = createGet(request, MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<UserVO> owners = parseUserArray(body);
    assertNotNull(owners);
    assertEquals(owners.size(), 2);

    Long idKey1 = null;
    Long idKey2 = null;
    for (final UserVO participant : owners) {
        if (participant.getKey().equals(owner1.getKey())) {
            idKey1 = owner1.getKey();
        } else if (participant.getKey().equals(owner2.getKey())) {
            idKey2 = owner2.getKey();
        }
    }
    assertNotNull(idKey1);
    assertNotNull(idKey2);
}
 
Example 6
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetUsers() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);
    final List<Identity> identities = securityManager.getIdentitiesByPowerSearch(null, null, true, null, null, null, null, null, null, null,
            Identity.STATUS_VISIBLE_LIMIT);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
    assertEquals(vos.size(), identities.size());
}
 
Example 7
Source File: CoursesITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCourses() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/repo/courses", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    final List<CourseVO> courses = parseCourseArray(body);
    assertNotNull(courses);
    assertTrue(courses.size() >= 2);

    CourseVO vo1 = null;
    CourseVO vo2 = null;
    for (final CourseVO course : courses) {
        if (course.getTitle().equals("courses1")) {
            vo1 = course;
        } else if (course.getTitle().equals("courses2")) {
            vo2 = course;
        }
    }
    assertNotNull(vo1);
    assertEquals(vo1.getKey(), course1.getResourceableId());
    assertNotNull(vo2);
    assertEquals(vo2.getKey(), course2.getResourceableId());
}
 
Example 8
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetUsers() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final List<UserVO> vos = parseUserArray(body);
    final List<Identity> identities = securityManager.getIdentitiesByPowerSearch(null, null, true, null, null, null, null, null, null, null,
            Identity.STATUS_VISIBLE_LIMIT);

    assertNotNull(vos);
    assertFalse(vos.isEmpty());
    assertEquals(vos.size(), identities.size());
}
 
Example 9
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetUserNotAdmin() throws IOException {
    final HttpClient c = loginWithCookie("rest-one", "A6B7C8");

    final HttpMethod method = createGet("/users/" + id2.getKey(), MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String body = method.getResponseBodyAsString();
    method.releaseConnection();
    final UserVO vo = parse(body, UserVO.class);

    assertNotNull(vo);
    assertEquals(vo.getKey(), id2.getKey());
    assertEquals(vo.getLogin(), id2.getName());
    // no properties for security reason
    assertTrue(vo.getProperties().isEmpty());
}
 
Example 10
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Only print out the raw body of the response
 * 
 * @throws IOException
 */
@Test
public void testGetRawXmlUser() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");
    final HttpMethod method = createGet("/users/" + id1.getKey(), MediaType.APPLICATION_XML, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String bodyXml = method.getResponseBodyAsString();
    System.out.println("User");
    System.out.println(bodyXml);
    System.out.println("User");
}
 
Example 11
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Only print out the raw body of the response
 * 
 * @throws IOException
 */
@Test
public void testGetRawXmlUsers() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/users", MediaType.APPLICATION_XML, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String bodyXmls = method.getResponseBodyAsString();
    System.out.println("Users XML");
    System.out.println(bodyXmls);
    System.out.println("Users XML");
}
 
Example 12
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Only print out the raw body of the response
 * 
 * @throws IOException
 */
@Test
public void testGetRawJsonUser() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/users/" + id1.getKey(), MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String bodyJson = method.getResponseBodyAsString();
    System.out.println("User");
    System.out.println(bodyJson);
    System.out.println("User");
}
 
Example 13
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Only print out the raw body of the response
 * 
 * @throws IOException
 */
@Test
public void testGetRawJsonUser() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/users/" + id1.getKey(), MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String bodyJson = method.getResponseBodyAsString();
    System.out.println("User");
    System.out.println(bodyJson);
    System.out.println("User");
}
 
Example 14
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Only print out the raw body of the response
 * 
 * @throws IOException
 */
@Test
public void testGetRawJsonUsers() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String bodyJsons = method.getResponseBodyAsString();
    System.out.println("Users JSON");
    System.out.println(bodyJsons);
    System.out.println("Users JSON");
}
 
Example 15
Source File: SubmitCert.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static void sendRequest(String url) {
    try {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        int responseCode = client.executeMethod(method);
        String is = method.getResponseBodyAsString();
        s_logger.info("Response code " + responseCode + ": " + is);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
 
Example 16
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 5 votes vote down vote up
Set<String> getUpdateDataIdsInBody(HttpMethod httpMethod) {
    Set<String> modifiedDataIdSet = new HashSet<String>();
    try {
        String modifiedDataIdsString = httpMethod.getResponseBodyAsString();
        return convertStringToSet(modifiedDataIdsString);
    }
    catch (Exception e) {

    }
    return modifiedDataIdSet;

}
 
Example 17
Source File: UserMgmtITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Only print out the raw body of the response
 * 
 * @throws IOException
 */
@Test
public void testGetRawJsonUsers() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final HttpMethod method = createGet("/users", MediaType.APPLICATION_JSON, true);
    final int code = c.executeMethod(method);
    assertEquals(code, 200);
    final String bodyJsons = method.getResponseBodyAsString();
    System.out.println("Users JSON");
    System.out.println(bodyJsons);
    System.out.println("Users JSON");
}
 
Example 18
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
*/
  @Override
  public MediaResource getAsyncMediaResource(final UserRequest ureq) {

      final String moduleURI = ureq.getModuleURI();
      // FIXME:fj: can we distinguish between a ../ call an a click to another component?
      // now works for start uri's like /demo/tunneldemo.php but when in tunneldemo.php
      // a link is used like ../ this link does not work (moduleURI is null). if i use
      // ../index.php instead everything works as expected
      if (moduleURI == null) { // after a click on some other component e.g.
          if (!firstCall) {
              return null;
          }
          firstCall = false; // reset first call
      }

      final TURequest tureq = new TURequest(config, ureq);

      // if (allowedToSendPersonalHeaders) {
      final String userName = ureq.getIdentity().getName();
      final User u = ureq.getIdentity().getUser();
      final String lastName = getUserService().getUserProperty(u, UserConstants.LASTNAME, loc);
      final String firstName = getUserService().getUserProperty(u, UserConstants.FIRSTNAME, loc);
      final String email = getUserService().getUserProperty(u, UserConstants.EMAIL, loc);
      tureq.setEmail(email);
      tureq.setFirstName(firstName);
      tureq.setLastName(lastName);
      tureq.setUserName(userName);
      // }

      final HttpMethod meth = fetch(tureq, httpClientInstance);
      if (meth == null) {
          setFetchError();
          return null;
      }

      final Header responseHeader = meth.getResponseHeader("Content-Type");
      if (responseHeader == null) {
          setFetchError();
          return null;
      }

      final String mimeType = responseHeader.getValue();
      if (mimeType != null && mimeType.startsWith("text/html")) {
          // we have html content, let doDispatch handle it for
          // inline rendering, update hreq for next content request
          String body;
          try {
              body = meth.getResponseBodyAsString();
          } catch (final IOException e) {
              log.warn("Problems when tunneling URL::" + tureq.getUri(), e);
              return null;
          }
          final SimpleHtmlParser parser = new SimpleHtmlParser(body);
          if (!parser.isValidHtml()) { // this is not valid HTML, deliver
              // asynchronuous
              return new HttpRequestMediaResource(meth);
          }
          meth.releaseConnection();
          htmlHead = parser.getHtmlHead();
          jsOnLoad = parser.getJsOnLoad();
          htmlContent = parser.getHtmlContent();
          setDirty(true);
      } else {
          return new HttpRequestMediaResource(meth); // this is a async browser
      }
      // refetch
      return null;
  }
 
Example 19
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
private void fetchFirstResource(final Identity ident) {

        final TURequest tureq = new TURequest(); // config, ureq);
        tureq.setContentType(null); // not used
        tureq.setMethod("GET");
        tureq.setParameterMap(Collections.EMPTY_MAP);
        tureq.setQueryString(query);
        if (startUri != null) {
            if (startUri.startsWith("/")) {
                tureq.setUri(startUri);
            } else {
                tureq.setUri("/" + startUri);
            }
        }

        // if (allowedToSendPersonalHeaders) {
        final String userName = ident.getName();
        final User u = ident.getUser();
        final String lastName = getUserService().getUserProperty(u, UserConstants.LASTNAME, loc);
        final String firstName = getUserService().getUserProperty(u, UserConstants.FIRSTNAME, loc);
        final String email = getUserService().getUserProperty(u, UserConstants.EMAIL, loc);

        tureq.setEmail(email);
        tureq.setFirstName(firstName);
        tureq.setLastName(lastName);
        tureq.setUserName(userName);
        // }

        final HttpMethod meth = fetch(tureq, httpClientInstance);
        if (meth == null) {
            setFetchError();
        } else {

            final Header responseHeader = meth.getResponseHeader("Content-Type");
            String mimeType;
            if (responseHeader == null) {
                setFetchError();
                mimeType = null;
            } else {
                mimeType = responseHeader.getValue();
            }

            if (mimeType != null && mimeType.startsWith("text/html")) {
                // we have html content, let doDispatch handle it for
                // inline rendering, update hreq for next content request
                String body;
                try {
                    body = meth.getResponseBodyAsString();
                } catch (final IOException e) {
                    log.warn("Problems when tunneling URL::" + tureq.getUri(), e);
                    htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": Unknown transfer problem '";
                    return;
                }
                final SimpleHtmlParser parser = new SimpleHtmlParser(body);
                if (!parser.isValidHtml()) { // this is not valid HTML, deliver
                    // asynchronuous
                }
                meth.releaseConnection();
                htmlHead = parser.getHtmlHead();
                jsOnLoad = parser.getJsOnLoad();
                htmlContent = parser.getHtmlContent();
            } else {
                htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": mime type was '" + mimeType + "' but expected 'text/html'. Response header was '"
                        + responseHeader + "'.";
            }
        }
    }
 
Example 20
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
private void fetchFirstResource(final Identity ident) {

        final TURequest tureq = new TURequest(); // config, ureq);
        tureq.setContentType(null); // not used
        tureq.setMethod("GET");
        tureq.setParameterMap(Collections.EMPTY_MAP);
        tureq.setQueryString(query);
        if (startUri != null) {
            if (startUri.startsWith("/")) {
                tureq.setUri(startUri);
            } else {
                tureq.setUri("/" + startUri);
            }
        }

        // if (allowedToSendPersonalHeaders) {
        final String userName = ident.getName();
        final User u = ident.getUser();
        final String lastName = getUserService().getUserProperty(u, UserConstants.LASTNAME, loc);
        final String firstName = getUserService().getUserProperty(u, UserConstants.FIRSTNAME, loc);
        final String email = getUserService().getUserProperty(u, UserConstants.EMAIL, loc);

        tureq.setEmail(email);
        tureq.setFirstName(firstName);
        tureq.setLastName(lastName);
        tureq.setUserName(userName);
        // }

        final HttpMethod meth = fetch(tureq, httpClientInstance);
        if (meth == null) {
            setFetchError();
        } else {

            final Header responseHeader = meth.getResponseHeader("Content-Type");
            String mimeType;
            if (responseHeader == null) {
                setFetchError();
                mimeType = null;
            } else {
                mimeType = responseHeader.getValue();
            }

            if (mimeType != null && mimeType.startsWith("text/html")) {
                // we have html content, let doDispatch handle it for
                // inline rendering, update hreq for next content request
                String body;
                try {
                    body = meth.getResponseBodyAsString();
                } catch (final IOException e) {
                    log.warn("Problems when tunneling URL::" + tureq.getUri(), e);
                    htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": Unknown transfer problem '";
                    return;
                }
                final SimpleHtmlParser parser = new SimpleHtmlParser(body);
                if (!parser.isValidHtml()) { // this is not valid HTML, deliver
                    // asynchronuous
                }
                meth.releaseConnection();
                htmlHead = parser.getHtmlHead();
                jsOnLoad = parser.getJsOnLoad();
                htmlContent = parser.getHtmlContent();
            } else {
                htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": mime type was '" + mimeType + "' but expected 'text/html'. Response header was '"
                        + responseHeader + "'.";
            }
        }
    }