类org.apache.http.client.fluent.Content源码实例Demo

下面列出了怎么用org.apache.http.client.fluent.Content的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: my_curd   文件: DownBook.java
/**
 * Get 请求代理
 *
 * @param url
 * @return
 */
public static String getProxy(String url) {
    log.info(" ---- get url: {}", url);

    String resStr = null;
    Content content;
    try {
        content = Request.Get(url).setHeader("User-Agent", userAgents[RandomUtils.number(0, userAgents.length)])
                .connectTimeout(connectTimeout).execute().returnContent();
        resStr = content.asString(Charset.forName(charset));
        log.debug(resStr);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    return resStr;
}
 
@Before
public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        metricSourceSinkConfig = ConfigFactory.parseMap(metricSourceSinkConfigMap);
        String functionsInputFile = "config/functions-test.txt";
        metricFunctionsSpec = MetricFunctionsReader
                        .readFromInputFile(ClassLoader.getSystemResource(functionsInputFile).getPath()).get(0);
        String validGraphiteResponse = readFile("tests/validGraphiteResponse.json");
        Content validGraphiteResponseContent = new Content(validGraphiteResponse.getBytes(),
                        ContentType.APPLICATION_JSON);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583039039&until=1583039099",
                        graphiteHeaders)).thenReturn(validGraphiteResponseContent);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583039039&until=1583039099",
                        metrictankHeaders)).thenReturn(validGraphiteResponseContent);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(d.e.f)&from=1583039039&until=1583039099",
                        graphiteHeaders)).thenReturn(validGraphiteResponseContent);

        String validGraphiteResponseWithNull = readFile("tests/validGraphiteResponseWithNull.json");
        Content validGraphiteResponseWithNullContent = new Content(validGraphiteResponseWithNull.getBytes(),
                        ContentType.APPLICATION_JSON);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583125439&until=1583125499",
                        graphiteHeaders)).thenReturn(validGraphiteResponseWithNullContent);

        String invalidGraphiteResponse = readFile("tests/invalidGraphiteResponse.json");
        Content invalidGraphiteResponseContent = new Content(invalidGraphiteResponse.getBytes(),
                        ContentType.APPLICATION_JSON);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583211839&until=1583211899",
                        graphiteHeaders)).thenReturn(invalidGraphiteResponseContent);

        Content emptyGraphiteResponseContent = new Content("[]".getBytes(), ContentType.APPLICATION_JSON);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583298239&until=1583298299",
                        graphiteHeaders)).thenReturn(emptyGraphiteResponseContent);
}
 
源代码3 项目: adaptive-alerting   文件: HttpClientWrapper.java
/**
 * Makes an HTTP GET call with headers to the given URI and returns the result.
 *
 * @param uri URI
 * @return Call result
 * @throws IOException if there's a problem making the call
 */
public Content get(String uri, Map<String, String> headers) throws IOException {
    if (headers.isEmpty()) {
        return get(uri);
    }
    val getRequest = Request.Get(uri);
    return buildRequestWithHeaders(getRequest, headers)
            .execute()
            .returnContent();
}
 
源代码4 项目: demo   文件: ApiCalls.java
/**
 * Use the API to register a user
 * @param username some username
 * @param password a really good password (otherwise it will probably respond with a complaint
 * @return returns the body of the result, if you wish to use it.
 */
public static String registerUser(String username, String password) {
    try {
        final Content content = Request.Post("http://localhost:8080/demo/register")
                .bodyForm(Form.form().add("username", username).add("password", password).build())
                .execute().returnContent();
        return content.asString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
源代码5 项目: demo   文件: ApiCalls.java
public static String registerBook(String title) {
    try {
        final Content content = Request.Post("http://localhost:8080/demo/registerbook")
                .bodyForm(Form.form().add("book", title).build())
                .execute().returnContent();
        return content.asString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
源代码6 项目: demo   文件: ApiCalls.java
public static String registerBorrowers(String name) {
    try {
        final Content content = Request.Post("http://localhost:8080/demo/registerborrower")
                .bodyForm(Form.form().add("borrower", name).build())
                .execute().returnContent();
        return content.asString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
源代码7 项目: javabase   文件: Test.java
public static void main(String[] args) throws IOException {
    Content dd = Request.Post("http://s.dianping.com/ajax/json/activity/offline/followNoteAdd")
            .addHeader("Cookie", "isChecked=checked; JSESSIONID=5F9986BAAD08E91A40A18F9B16207DF0; _hc.v=7ff280b3-a676-c8dc-1a84-e5c9067f4dce.1534824829; _lxsdk_cuid=1655ab04f9ac8-00e38d0412b1cf-34677909-1fa400-1655ab04f9bc8; _lxsdk=1655ab04f9ac8-00e38d0412b1cf-34677909-1fa400-1655ab04f9bc8; cityid=1; citypinyin=shanghai; cityname=5LiK5rW3; s_ViewType=10; Hm_lvt_4c4fc10949f0d691f3a2cc4ca5065397=1534137110,1534904349; m_flash2=1; dper=d0a06116fb82790b7f4b503d4d3819545532d655172fbcce35647455fd2970d565f1c804897a94a679d5f9ea51178e6a77bdd3aa929cc272531255fda8f4c9869554ee3733589bd55adf4a5b7281ab234461678ea971200d578e18f7aef57fc2; ll=7fd06e815b796be3df069dec7836c3df; ua=18638217959; Hm_lpvt_4c4fc10949f0d691f3a2cc4ca5065397=1534904979; edper=0a7c1b58f873e7f2d6b8cc9821f469e2b7bb79faed2ed581c1592876d7643944; aburl=1; cye=dplab; ta.uuid=1032881519540281362; isUuidUnion=true; iuuid=1655ab04f9ac8-00e38d0412b1cf-34677909-1fa400-1655ab04f9bc8; dpUserId=21304984; mtUserId=\"\"; pvhistory=\"6L+U5ZuePjo8L3N0YXRpY3Rlc3QvbG9nZXZlbnQ/bmFtZT1XaGVyZUFtSUZhaWwmaW5mbz1odG1sLSU1QiU3QiUyMmNvZGUlMjIlM0EzJTJDJTIybWVzc2FnZSUyMiUzQSUyMlRpbWVvdXQlMjBleHBpcmVkJTIyJTdEJTVEJmNhbGxiYWNrPVdoZXJlQW1JMTE1MzUwOTMxMjk2OTI+OjwxNTM1MDkzMTI5NzU5XV9b\"; ri=1000310100; m_set_info=%7B%22ri%22%3A%221000310100%22%2C%22rv%22%3A%221535093140885%22%2C%22ui%22%3A%226081504%22%7D; rv=1535093140885; cy=1; _lx_utm=utm_source%3Ddp_pc_event; _lxsdk_s=1656aecd48d-b4d-6d4-d8d%7C%7C96")
            .bodyForm(Form.form().add("offlineActivityId", "504460353").add("noteBody", "ddd").build())
            .execute().returnContent();
    log.info(dd.asString());
}
 
源代码8 项目: thorntail   文件: MvcTest.java
@Test
@RunAsClient
public void testGettingView() throws IOException {
    Response response = Request.Get(baseUrl.toString() + "/hello").execute();
    Content content = response.returnContent();
    assertThat(content.asString(), containsString("Hello World!"));
}
 
@RunAsClient
@Test
public void tokenIsNotProcessed() throws Exception {
    Content content = Request.Get("http://localhost:8080/mpjwt/subject/secured/json-web-token")
            .setHeader("Authorization", "Bearer " + createToken("MappedRole"))
            .execute().returnContent();
    assertThat(content).isNull();
}
 
@RunAsClient
@Test
public void subjectShouldNotLeakToNonSecuredRequest() throws Exception {
    // project-no-roles-props.yml restricts the number of worker threads to 1,
    // that is, all requests are processed by the same single thread

    String response = Request.Get("http://localhost:8080/mpjwt/subject/secured/json-web-token")
            .setHeader("Authorization", "Bearer " + createToken("MappedRole"))
            .execute().returnContent().asString();
    assertThat(response).isEqualTo(TokenUtils.SUBJECT);

    Content content = Request.Get("http://localhost:8080/mpjwt/subject/unsecured/json-web-token")
            .execute().returnContent();
    assertThat(content).isNull();
}
 
private void checkSubjectShouldNotLeakToNonSecuredRequest(String pathSegment) throws Exception {
    // project-no-roles-props.yml restricts the number of worker threads to 1,
    // that is, all requests are processed by the same single thread
    Content content = Request.Get("http://localhost:8080/mpjwt/subject/unsecured" + pathSegment)
            .execute().returnContent();
    assertThat(content).isNull();
}
 
源代码12 项目: thorntail   文件: MpJwtDisabledTest.java
@RunAsClient
@Test
public void tokenIsNotProcessed() throws Exception {
    Content content = Request.Get("http://localhost:8080/mpjwt/subject/secured/json-web-token")
            .setHeader("Authorization", "Bearer " + createToken("MappedRole"))
            .execute().returnContent();
    assertThat(content).isNull();
}
 
源代码13 项目: thorntail   文件: PrincipalLeakTest.java
private void checkSubjectShouldNotLeakToNonSecuredRequest(String pathSegment) throws Exception {
    // project-no-roles-props.yml restricts the number of worker threads to 1,
    // that is, all requests are processed by the same single thread
    Content content = Request.Get("http://localhost:8080/mpjwt/subject/unsecured" + pathSegment)
            .execute().returnContent();
    assertThat(content).isNull();
}
 
源代码14 项目: james-project   文件: UploadStepdefs.java
@Given("^\"([^\"]*)\" is starting uploading a content$")
public void userStartUploadContent(String username) {
    AccessToken accessToken = userStepdefs.authenticate(username);

    CountDownLatch startSignal = new CountDownLatch(2);
    CountDownConsumeInputStream bodyStream = new CountDownConsumeInputStream(startSignal);
    Request request = Request.Post(uploadUri)
        .bodyStream(new BufferedInputStream(bodyStream, _1M), org.apache.http.entity.ContentType.DEFAULT_BINARY);
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.asString());
    }
    async = Async.newInstance().execute(request, new FutureCallback<Content>() {
        
        @Override
        public void failed(Exception ex) {
        }
        
        @Override
        public void completed(Content result) {
        }
        
        @Override
        public void cancelled() {
            bodyStream.getStartSignal().countDown();
            if (bodyStream.getStartSignal().getCount() == 1) {
                isCanceled = true;
            }
        }
    });
}
 
源代码15 项目: adaptive-alerting   文件: MetricQueryService.java
private MetricData queryGraphite(Config metricSourceSinkConfig, MetricFunctionsSpec metricFunctionsSpec,
        Instant instant) throws MetricQueryServiceException {
    Boolean success = true;
    String graphiteUrl = "";
    String logTimestamp = "";
    String logValue = "";
    String exceptionName = "";
    String errorMessage = "";
    try {

        String graphiteFunction = metricFunctionsSpec.getFunction();
        int intervalInSecs = metricFunctionsSpec.getIntervalInSecs();
        long currentTimestamp = instant.getEpochSecond();
        long snappedCurrentTimestamp = currentTimestamp - (currentTimestamp % intervalInSecs);

        String graphiteUrlTemplate = metricSourceSinkConfig.getString(GRAPHITE_URL_TEMPLATE_KEY);

        // Subtract 1 second from 'from' and 'until' timestamps to get complete data for
        // the interval -
        // otherwise Graphite gives incomplete data.
        long until = snappedCurrentTimestamp - 1;
        long from = until - intervalInSecs;

        graphiteUrl = String.format("%s%s&from=%d&until=%d", graphiteUrlTemplate, graphiteFunction, from, until);
        Map<String, String> headers = Collections.emptyMap();
        if (metricSourceSinkConfig.getString(IS_GRAPHITE_SERVER_METRICTANK_KEY)
                .equals(GRAPHITE_SERVER_METRICTANK)) {
            /* default metrictank orgId */
            headers = Collections.singletonMap("x-org-id", "1");
        }
        Content graphiteResponse = metricFunctionHttpClient.get(graphiteUrl, headers);
        ObjectMapper objectMapper = new ObjectMapper();
        List<GraphiteResult> graphiteResults = Arrays
                .asList(objectMapper.readValue(graphiteResponse.asBytes(), GraphiteResult[].class));
        for (GraphiteResult graphiteResult : graphiteResults) {
            Datapoint datapoint = graphiteResult.getDatapoint();
            logValue = String.valueOf(datapoint.getValue());
            logTimestamp = String.valueOf(datapoint.getTimestamp());

            HashMap<String, String> tagsBuilder = new HashMap<>();
            tagsBuilder.putAll(metricFunctionsSpec.getTags());
            if (metricFunctionsSpec.getMergeTags())
                tagsBuilder.putAll(graphiteResult.getTags());

            TagCollection tags = new TagCollection(tagsBuilder);
            TagCollection metaTags = TagCollection.EMPTY;
            MetricDefinition metricDefinition = new MetricDefinition(graphiteFunction, tags, metaTags);
            String infoMessage = String.format(
                    "step=queryGraphiteSource,success=%s,exception=%s,url=\"%s\",timestamp=%s,value=%s", success,
                    exceptionName, graphiteUrl, logTimestamp, logValue);
            log.info(infoMessage);
            return new MetricData(metricDefinition, datapoint.getValue(), datapoint.getTimestamp());
        }
        throw new MissingDatapointException();
    } catch (Exception e) {
        success = false;
        exceptionName = e.getClass().getSimpleName();
        errorMessage = String.format("step=queryGraphiteSource,success=%s,exception=%s,url=\"%s\"", success,
                exceptionName, graphiteUrl);
        throw new MetricQueryServiceException(errorMessage, e);
    }
}
 
源代码16 项目: adaptive-alerting   文件: HttpClientWrapper.java
/**
 * Makes an HTTP POST call to the given URI with given body and returns the result.
 *
 * @param uri  the uri
 * @param body the body
 * @return Call result
 * @throws IOException the io exception
 */
@Generated // https://reflectoring.io/100-percent-test-coverage/
public Content post(String uri, String body) throws IOException {
    return Request.Post(uri)
            .bodyString(body, ContentType.APPLICATION_JSON)
            .execute()
            .returnContent();
}
 
源代码17 项目: adaptive-alerting   文件: HttpClientWrapper.java
/**
 * Makes an HTTP GET call to the given URI and returns the result.
 *
 * @param uri URI
 * @return Call result
 * @throws IOException if there's a problem making the call
 */
public Content get(String uri) throws IOException {
    return Request.Get(uri)
            .execute()
            .returnContent();
}
 
 类所在包
 类方法
 同包方法