org.apache.cxf.jaxrs.client.WebClient类的使用及代码示例

x33g5p2x  于2022-02-02 转载在 其他  
字(11.6k)|赞(0)|评价(0)|浏览(146)

本文整理了Java中org.apache.cxf.jaxrs.client.WebClient类的一些代码示例,展示了WebClient类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。WebClient类的具体详情如下:
包路径:org.apache.cxf.jaxrs.client.WebClient
类名称:WebClient

WebClient介绍

[英]Http-centric web client
[中]以Http为中心的web客户端

代码示例

代码示例来源:origin: apache/tika

@Test
public void testFloatInHeader() {
  Response response = WebClient.create(endPoint + TIKA_PATH)
      .type("application/pdf")
      .accept("text/plain")
      .header(TikaResource.X_TIKA_PDF_HEADER_PREFIX +
              "averageCharTolerance",
          "2.0")
      .put(ClassLoader.getSystemResourceAsStream("testOCR.pdf"));
  assertEquals(200, response.getStatus());
}

代码示例来源:origin: apache/tika

@Test
public void testHelloWorld() throws Exception {
  Response response = WebClient.create(endPoint + TIKA_PATH)
      .type("text/plain").accept("text/plain").get();
  assertEquals(TikaResource.GREETING,
      getStringFromInputStream((InputStream) response.getEntity()));
}

代码示例来源:origin: apache/tika

/**
 * recognises names of entities in the text
 * @param text text which possibly contains names
 * @return map of entity type -> set of names
 */
public Map<String, Set<String>> recognise(String text) {
  Map<String, Set<String>> entities = new HashMap<>();
  try {
    String url = restHostUrlStr + "/nltk";
    Response response = WebClient.create(url).accept(MediaType.TEXT_HTML).post(text);
    int responseCode = response.getStatus();
    if (responseCode == 200) {
      String result = response.readEntity(String.class);
      JSONParser parser = new JSONParser();
      JSONObject j = (JSONObject) parser.parse(result);
      Iterator<?> keys = j.keySet().iterator();
      while( keys.hasNext() ) {
        String key = (String)keys.next();
        if ( !key.equals("result") ) {
          ENTITY_TYPES.add(key);
          entities.put(key.toUpperCase(Locale.ENGLISH), new HashSet((Collection) j.get(key)));
        }
      }
    }
  }
  catch (Exception e) {
    LOG.debug(e.getMessage(), e);
  }
  return entities;
}

代码示例来源:origin: apache/tika

protected static boolean canRun() {
  Response response = null;
  try {
    response = WebClient.create(readRestUrl() + GROBID_ISALIVE_PATH)
        .accept(MediaType.TEXT_HTML).get();
    String resp = response.readEntity(String.class);
    return resp != null && !resp.equals("") && resp.startsWith("<h4>");
  } catch (Exception e) {
    //swallow...can't run
    return false;
  }
}

代码示例来源:origin: apache/tika

protected static boolean canRun() {
    try {
      Response response = WebClient
          .create(TEXT_REST_HOST + TEXT_LID_PATH)
          .get();
      String json = response.readEntity(String.class);
      JsonArray jsonArray = new JsonParser().parse(json).getAsJsonObject().get("all_languages").getAsJsonArray();
      return jsonArray.size() != 0;
    } catch (Exception e) {
      LOG.warn("Can't run", e);
      return false;
    }
  }
}

代码示例来源:origin: apache/tika

/**
 * Detects the content's language using the Lingo24 API.
 * @param content the <code>String</code> content to be used for detection
 * @return the language detected or <code>null</code> if detection failed
 */
private String detect(String content) {
  String language = null;
  if (!isAvailable) {
    return language;
  }
  Form form = new Form();
  form.param("user_key", userKey);
  form.param("q", content);
  Response response = client.accept(MediaType.APPLICATION_JSON).form(form);
  String json = response.readEntity(String.class);
  JsonElement element = new JsonParser().parse(json);
  if (element.getAsJsonObject().get("success") != null &&
      element.getAsJsonObject().get("success").getAsString().equals("true")) {
    language = element.getAsJsonObject().get("lang").getAsString();
  }
  return language;
}

代码示例来源:origin: apache/cxf

@org.junit.Test
public void testBadEncryptingKey() throws Exception {
  URL busFile = JweJwsAlgorithmTest.class.getResource("client.xml");
  List<Object> providers = new ArrayList<>();
  providers.add(new JacksonJsonProvider());
  providers.add(new JweWriterInterceptor());
  String address = "http://localhost:" + PORT + "/jweoaepgcm/bookstore/books";
  WebClient client =
    WebClient.create(address, providers, busFile.toString());
  client.type("application/json").accept("application/json");
  Map<String, Object> properties = new HashMap<>();
  properties.put("rs.security.keystore.type", "jwk");
  properties.put("rs.security.keystore.alias", "AliceCert");
  properties.put("rs.security.keystore.file", "org/apache/cxf/systest/jaxrs/security/certs/jwkPublicSet.txt");
  properties.put("rs.security.encryption.content.algorithm", "A128GCM");
  properties.put("rs.security.encryption.key.algorithm", "RSA-OAEP");
  WebClient.getConfig(client).getRequestContext().putAll(properties);
  Response response = client.post(new Book("book", 123L));
  assertNotEquals(response.getStatus(), 200);
}

代码示例来源:origin: apache/cxf

@Test
public void testEchoBook() throws Exception {
  URL url = new URL("http://localhost:" + PORT + "/test/5/bookstorestorage/thosebooks");
  WebClient wc = WebClient.create(url.toString(),
                  Collections.singletonList(new CustomJaxbElementProvider()));
  Response r = wc.type("application/xml").post(new Book("proxy", 333L));
  Book book = r.readEntity(Book.class);
  assertEquals(333L, book.getId());
  String ct = r.getHeaderString("Content-Type");
  assertEquals("application/xml;a=b", ct);
}

代码示例来源:origin: apache/cxf

@org.junit.Test
public void testServiceWithFakeToken() throws Exception {
  URL busFile = OAuth2FiltersTest.class.getResource("client.xml");
  // Now invoke on the service with the faked access token
  String address = "https://localhost:" + PORT + "/secured/bookstore/books";
  WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                    busFile.toString());
  client.header("Authorization", "Bearer " + UUID.randomUUID().toString());
  Response response = client.post(new Book("book", 123L));
  assertNotEquals(response.getStatus(), 200);
}

代码示例来源:origin: apache/cxf

@org.junit.Test
public void testAuthorizationCodeBadScope() throws Exception {
  URL busFile = AuthorizationGrantTest.class.getResource("client.xml");
  String address = "https://localhost:" + port + "/services/";
  WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                    "alice", "security", busFile.toString());
  // Save the Cookie for the second request...
  WebClient.getConfig(client).getRequestContext().put(
    org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
  // Get Authorization Code
  // Make initial authorization request
  client.type("application/json").accept("application/json");
  client.query("client_id", "consumer-id");
  client.query("response_type", "code");
  client.query("redirect_uri", "http://www.blah.bad.apache.org");
  client.query("scope", "unknown-scope");
  client.path("authorize/");
  // No redirect URI
  Response response = client.get();
  assertEquals(400, response.getStatus());
}

代码示例来源:origin: apache/cxf

@Test
public void testNoHttpSignature() throws Exception {
  URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");
  String address = "https://localhost:" + PORT + "/httpsig/bookstore/books";
  WebClient client =
    WebClient.create(address, busFile.toString());
  client.type("application/xml").accept("application/xml");
  Response response = client.post(new Book("CXF", 126L));
  assertEquals(response.getStatus(), 400);
}

代码示例来源:origin: apache/cxf

@org.junit.Test
public void testGetClientRegNotAvail() throws Exception {
  URL busFile = OIDCDynamicRegistrationTest.class.getResource("client.xml");
  String address = "https://localhost:" + PORT + "/services/dynamic/register";
  WebClient wc = WebClient.create(address, Collections.singletonList(new JsonMapObjectProvider()),
           busFile.toString());
  Response r = wc.accept("application/json").path("some-client-id").get();
  assertEquals(401, r.getStatus());
}
@org.junit.Test

代码示例来源:origin: apache/cxf

@Test
public void testInvalidSAMLTokenAsHeader() throws Exception {
  String address = "https://localhost:" + PORT + "/samlheader/bookstore/books/123";
  JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
  bean.setAddress(address);
  SpringBusFactory bf = new SpringBusFactory();
  URL busFile = JAXRSSamlTest.class.getResource("client.xml");
  Bus springBus = bf.createBus(busFile.toString());
  bean.setBus(springBus);
  WebClient wc = bean.createWebClient();
  wc.header("Authorization", "SAML invalid_grant");
  Response r = wc.get();
  assertEquals(401, r.getStatus());
}

代码示例来源:origin: apache/cxf

@org.junit.Test
public void testGetKeys() throws Exception {
  URL busFile = OIDCFlowTest.class.getResource("client.xml");
  String address = "https://localhost:" + port + "/services/";
  WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                    "alice", "security", busFile.toString());
  client.accept("application/json");
  client.path("keys/");
  Response response = client.get();
  JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);
  assertEquals(1, jsonWebKeys.getKeys().size());
}

代码示例来源:origin: apache/cxf

private WebClient createWebClient() {
  URL busFile = JAXRSJcsTest.class.getResource("client.xml");
  List<Object> providers = new ArrayList<>();
  String address = "https://localhost:" + PORT + "/jcs/bookstore/books";
  WebClient client =
    WebClient.create(address, providers, busFile.toString());
  client.type("application/json").accept("application/json");
  return client;
}

代码示例来源:origin: apache/cxf

private WebClient createWebClient(String address) {
  JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
  bean.setAddress(address);
  SpringBusFactory bf = new SpringBusFactory();
  URL busFile = JAXRSOAuth2Test.class.getResource("client.xml");
  Bus springBus = bf.createBus(busFile.toString());
  bean.setBus(springBus);
  WebClient wc = bean.createWebClient();
  wc.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);
  return wc;
}

代码示例来源:origin: apache/cxf

@Test
public void testThatResponseValidationForOneResponseBookFails()  {
  Response r = createWebClient("/bookstore/booksResponse/1234").get();
  assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), r.getStatus());
  r = createWebClient("/bookstore/books").post(new Form().param("id", "1234"));
  assertEquals(Status.CREATED.getStatusCode(), r.getStatus());
  r = createWebClient("/bookstore/booksResponse/1234").get();
  assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), r.getStatus());
}

代码示例来源:origin: apache/cxf

@Test
public void testGetServicesPageNotFound() throws Exception {
  final String address = "http://localhost:" + PORT + "/the/services;a=b";
  WebClient wc = WebClient.create(address).accept("text/*");
  WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000);
  assertEquals(404, wc.get().getStatus());
}
@Test

代码示例来源:origin: apache/cxf

@Test
public void testAddAndQueryOneBook() {
  final String id = UUID.randomUUID().toString();
  Response r = createWebClient(getBasePath() + "/books").post(
      new Form()
          .param("id", id)
          .param("name", "Book 1234"));
  assertEquals(Response.Status.CREATED.getStatusCode(), r.getStatus());
  r = createWebClient(getBasePath() + "/books").path(id).get();
  assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
  Book book = r.readEntity(Book.class);
  assertEquals(id, book.getId());
}

代码示例来源:origin: apache/cxf

@Test
public void testPostAnd401WithText() throws Exception {
  String endpointAddress =
    "http://localhost:" + PORT + "/bookstore/post401";
  WebClient wc = WebClient.create(endpointAddress);
  WebClient.getConfig(wc).getHttpConduit().getClient().setAllowChunking(false);
  Response r = wc.post(null);
  assertEquals(401, r.getStatus());
  assertEquals("This is 401", getStringFromInputStream((InputStream)r.getEntity()));
}

相关文章

WebClient类方法