当前位置: 首页>>代码示例>>Java>>正文


Java HttpResponse类代码示例

本文整理汇总了Java中com.mashape.unirest.http.HttpResponse的典型用法代码示例。如果您正苦于以下问题:Java HttpResponse类的具体用法?Java HttpResponse怎么用?Java HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpResponse类属于com.mashape.unirest.http包,在下文中一共展示了HttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: processHttpRequest

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
public static String processHttpRequest(String completeURL,
                                        Map<String, Object> params,
                                        Map<String, String> customHeaders,
                                        HttpMethod method) throws IOException {

    Map<String, String> headers = getDefaultHeader();
    if (customHeaders != null) {
        headers.putAll(customHeaders);
    }

    HttpResponse<JsonNode> result = executeHttpMethod(completeURL, params, headers, method);
    if (result == null) {
        return null;
    }
    if (result.getStatus() != 200) {
        String exceptionResponse = result.getBody().toString();
        throw new ServiceException((result.getStatus() + result.getStatusText()),
                exceptionResponse);
    }
    return result.getBody().toString();
}
 
开发者ID:dixantmittal,项目名称:scalable-task-scheduler,代码行数:22,代码来源:HttpUtils.java

示例2: getAsJSONObject

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
/**
 * @return The json object get by performing request.
 */
public JSONObject getAsJSONObject() {
    JSONObject json;
    try {
        HttpResponse<JsonNode> response = request.asJson();
        checkRateLimit(response);
        handleErrorCode(response);
        JsonNode node = response.getBody();

        if (node.isArray()) {
            throw new UnirestException("The request returns a JSON Array. Json: "+node.getArray().toString(4));
        } else {
            json = node.getObject();
        }
    } catch (UnirestException e) {
        throw new JSONException("Error Occurred while getting JSON Object: "+e.getLocalizedMessage());
    }
    handleErrorResponse(json);
    return json;
}
 
开发者ID:AlienIdeology,项目名称:J-Cord,代码行数:23,代码来源:Requester.java

示例3: getAsJSONArray

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
/**
 * @return The json array get by performing request.
 */
public JSONArray getAsJSONArray() {
    JSONArray json;
    try {
        HttpResponse<JsonNode> response = request.asJson();
        checkRateLimit(response);
        handleErrorCode(response);
        JsonNode node = response.getBody();

        if (!node.isArray()) {
            handleErrorResponse(node.getObject());
            throw new UnirestException("The request returns a JSON Object. Json: "+node.getObject().toString(4));
        } else {
            json = node.getArray();
        }
    } catch (UnirestException e) {
        throw new JSONException("Error Occurred while getting JSON Array: "+e.getLocalizedMessage());
    }
    return json;
}
 
开发者ID:AlienIdeology,项目名称:J-Cord,代码行数:23,代码来源:Requester.java

示例4: download

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
public boolean download(String siaPath, Path destination) {
        LOGGER.info("downloading {}", siaPath);
//        final String dest = destination.toAbsolutePath().toString();
        final FileTime lastModified = SiaFileUtil.getFileTime(siaPath);

        final String tempFileName = destination.getFileName().toString() + ".tempdownload";
        Path tempFile = destination.getParent().resolve(tempFileName);
        final HttpResponse<String> downloadResult = siaCommand(SiaCommand.DOWNLOAD, ImmutableMap.of("destination", tempFile.toAbsolutePath().toString()), siaPath);
        final boolean noHosts = checkErrorFragment(downloadResult, NO_HOSTS);
        if (noHosts) {
            LOGGER.warn("unable to download file {} due to NO_HOSTS  ", siaPath);
            return false;
        }
        if (statusGood(downloadResult)) {
            try {
                Files.setLastModifiedTime(tempFile, lastModified);
                Files.move(tempFile, destination, StandardCopyOption.ATOMIC_MOVE);
                Files.setLastModifiedTime(destination, lastModified);
            } catch (IOException e) {
                throw new RuntimeException("unable to do atomic swap of file " + destination);
            }
            return true;
        }
        LOGGER.warn("unable to download siaPath {} for an unexpected reason: {} ", siaPath, downloadResult.getBody());
        return false;
    }
 
开发者ID:MineboxOS,项目名称:minebox,代码行数:27,代码来源:SiaUtil.java

示例5: test

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
@Test
public void test() throws UnirestException {
    gitHubSourceTask.config = new GitHubSourceConnectorConfig(initialConfig());
    gitHubSourceTask.nextPageToVisit = 1;
    gitHubSourceTask.nextQuerySince = Instant.parse("2017-01-01T00:00:00Z");
    gitHubSourceTask.gitHubHttpAPIClient = new GitHubAPIHttpClient(gitHubSourceTask.config);
    String url = gitHubSourceTask.gitHubHttpAPIClient.constructUrl(gitHubSourceTask.nextPageToVisit, gitHubSourceTask.nextQuerySince);
    System.out.println(url);
    HttpResponse<JsonNode> httpResponse = gitHubSourceTask.gitHubHttpAPIClient.getNextIssuesAPI(gitHubSourceTask.nextPageToVisit, gitHubSourceTask.nextQuerySince);
    if (httpResponse.getStatus() != 403) {
        assertEquals(200, httpResponse.getStatus());
        Set<String> headers = httpResponse.getHeaders().keySet();
        assertTrue(headers.contains("ETag"));
        assertTrue(headers.contains("X-RateLimit-Limit"));
        assertTrue(headers.contains("X-RateLimit-Remaining"));
        assertTrue(headers.contains("X-RateLimit-Reset"));
        assertEquals(batchSize.intValue(), httpResponse.getBody().getArray().length());
        JSONObject jsonObject = (JSONObject) httpResponse.getBody().getArray().get(0);
        Issue issue = Issue.fromJson(jsonObject);
        assertNotNull(issue);
        assertNotNull(issue.getNumber());
        assertEquals(2072, issue.getNumber().intValue());
    }
}
 
开发者ID:simplesteph,项目名称:kafka-connect-github-source,代码行数:25,代码来源:GitHubSourceTaskTest.java

示例6: testFileUpload

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
@Test
public void testFileUpload() throws Exception {

    app.post("/testFileUpload", ctx -> {
        File uploadedFile = createTempFile("Not expected content ...");
        FileUtils.copyInputStreamToFile(ctx.uploadedFile("upload").getContent(), uploadedFile);
        ctx.result(FileUtils.readFileToString(uploadedFile));
    });

    HttpResponse<String> response = Unirest.post(_UnirestBaseTest.origin + "/testFileUpload")
        .field("upload", createTempFile(EXPECTED_CONTENT))
        .asString();

    assertThat(response.getBody(), is(EXPECTED_CONTENT));

    app.stop();
}
 
开发者ID:tipsy,项目名称:javalin,代码行数:18,代码来源:TestFileUpload.java

示例7: getList

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
/**
 * Get List of records of response.
 *
 * @param response
 * @return
 */
private List<T> getList(HttpResponse<Records> response) {

    final Records records = response.getBody();
    final List<T> list = new ArrayList<>();

    for (Map<String, Object> record : records.getRecords()) {
        T item = null;
        try {
            item = transform(record, this.type.newInstance());
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            LOG.error(e.getMessage(), e);
        }
        list.add(item);
    }
    return list;
}
 
开发者ID:Sybit-Education,项目名称:airtable.java,代码行数:23,代码来源:Table.java

示例8: test_bodyReader

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
@Test
public void test_bodyReader() throws Exception {
    Javalin app = Javalin.create().port(0).start();
    app.before("/body-reader", ctx -> ctx.header("X-BEFORE", ctx.body() + ctx.queryParam("qp")));
    app.post("/body-reader", ctx -> ctx.result(ctx.body() + ctx.queryParam("qp")));
    app.after("/body-reader", ctx -> ctx.header("X-AFTER", ctx.body() + ctx.queryParam("qp")));

    HttpResponse<String> response = Unirest
        .post("http://localhost:" + app.port() + "/body-reader")
        .queryString("qp", "queryparam")
        .body("body")
        .asString();

    assertThat(response.getHeaders().getFirst("X-BEFORE"), is("bodyqueryparam"));
    assertThat(response.getBody(), is("bodyqueryparam"));
    assertThat(response.getHeaders().getFirst("X-AFTER"), is("bodyqueryparam"));
    app.stop();
}
 
开发者ID:tipsy,项目名称:javalin,代码行数:19,代码来源:TestBodyReading.java

示例9: getModelFromRemote

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
private Model getModelFromRemote(String graphQlQuery) {

        ObjectMapper mapper = new ObjectMapper();

        ObjectNode bodyParam = mapper.createObjectNode();

//        bodyParam.set("operationName", null);
//        bodyParam.set("variables", null);
        bodyParam.put("query", graphQlQuery);

        Model model = ModelFactory.createDefaultModel();

        try {
            HttpResponse<InputStream> response = Unirest.post(url)
                    .header("Accept", "application/rdf+xml")
                    .body(bodyParam.toString())
                    .asBinary();

            model.read(response.getBody(), "RDF/XML");

        } catch (UnirestException e) {
            e.printStackTrace();
        }

        return model;
    }
 
开发者ID:semantic-integration,项目名称:hypergraphql,代码行数:27,代码来源:HGraphQLService.java

示例10: getToken

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
@Override
public String getToken(String code) throws UnirestException {
    HttpResponse<JsonNode> response = Unirest.post("https://www.googleapis.com/oauth2/v4/token")
            .header("User-Agent", "pxls.space")
            .field("grant_type", "authorization_code")
            .field("code", code)
            .field("redirect_uri", getCallbackUrl())
            .field("client_id", App.getConfig().getString("oauth.google.key"))
            .field("client_secret", App.getConfig().getString("oauth.google.secret"))
            .asJson();

    JSONObject json = response.getBody().getObject();

    if (json.has("error")) {
        return null;
    } else {
        return json.getString("access_token");
    }
}
 
开发者ID:xSke,项目名称:Pxls,代码行数:20,代码来源:GoogleAuthService.java

示例11: getToken

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
public String getToken(String code) throws UnirestException {
    HttpResponse<JsonNode> response = Unirest.post("https://oauth.vk.com/access_token")
            .header("User-Agent", "pxls.space")
            .field("grant_type", "authorization_code")
            .field("code", code)
            .field("redirect_uri", getCallbackUrl())
            .field("client_id", App.getConfig().getString("oauth.vk.key"))
            .field("client_secret", App.getConfig().getString("oauth.vk.secret"))
            .asJson();

    JSONObject json = response.getBody().getObject();

    if (json.has("error")) {
        return null;
    } else {
        return json.getString("access_token");
    }
}
 
开发者ID:xSke,项目名称:Pxls,代码行数:19,代码来源:VKAuthService.java

示例12: getRedirectUrl

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
public String getRedirectUrl(String state) {
    try {
        HttpResponse<String> response = Unirest.get("https://www.tumblr.com/oauth/request_token?" + getOauthRequestToken("https://www.tumblr.com/oauth/request_token"))
            .header("User-Agent", "pxls.space")
            .asString();
        Map<String, String> query = parseQuery(response.getBody());
        if (!query.get("oauth_callback_confirmed").equals("true")) {
            return "/";
        }
        if (query.get("oauth_token") == null) {
            return "/";
        }
        tokens.put(query.get("oauth_token"), query.get("oauth_token_secret"));
        return "https://www.tumblr.com/oauth/authorize?oauth_token=" + query.get("oauth_token");
    } catch (UnirestException e) {
        return "/";
    }
}
 
开发者ID:xSke,项目名称:Pxls,代码行数:19,代码来源:TumblrAuthService.java

示例13: getToken

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
public String getToken(String code) throws UnirestException {
    HttpResponse<JsonNode> response = Unirest.post("https://discordapp.com/api/oauth2/token")
            .header("User-Agent", "pxls.space")
            .field("grant_type", "authorization_code")
            .field("code", code)
            .field("redirect_uri", getCallbackUrl())
            .basicAuth(App.getConfig().getString("oauth.discord.key"), App.getConfig().getString("oauth.discord.secret"))
            .asJson();

    JSONObject json = response.getBody().getObject();

    if (json.has("error")) {
        return null;
    } else {
        return json.getString("access_token");
    }
}
 
开发者ID:xSke,项目名称:Pxls,代码行数:18,代码来源:DiscordAuthService.java

示例14: getIdentifier

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
public String getIdentifier(String token) throws UnirestException, InvalidAccountException {
    HttpResponse<JsonNode> me = Unirest.get("https://discordapp.com/api/users/@me")
            .header("Authorization", "Bearer " + token)
            .header("User-Agent", "pxls.space")
            .asJson();
    JSONObject json = me.getBody().getObject();
    if (json.has("error")) {
        return null;
    } else {
        long id = json.getLong("id");
        long signupTimeMillis = (id >> 22) + 1420070400000L;
        long ageMillis = System.currentTimeMillis() - signupTimeMillis;

        long minAgeMillis = App.getConfig().getDuration("oauth.discord.minAge", TimeUnit.MILLISECONDS);
        if (ageMillis < minAgeMillis){
            long days = minAgeMillis / 86400 / 1000;
            throw new InvalidAccountException("Account too young");
        }
        return json.getString("id");
    }
}
 
开发者ID:xSke,项目名称:Pxls,代码行数:22,代码来源:DiscordAuthService.java

示例15: getIdentifier

import com.mashape.unirest.http.HttpResponse; //导入依赖的package包/类
public String getIdentifier(String token) throws UnirestException, InvalidAccountException {
    HttpResponse<JsonNode> me = Unirest.get("https://oauth.reddit.com/api/v1/me")
            .header("Authorization", "bearer " + token)
            .header("User-Agent", "pxls.space")
            .asJson();
    JSONObject json = me.getBody().getObject();
    if (json.has("error")) {
        return null;
    } else {
        long accountAgeSeconds = (System.currentTimeMillis() / 1000 - json.getLong("created"));
        long minAgeSeconds = App.getConfig().getDuration("oauth.reddit.minAge", TimeUnit.SECONDS);
        if (accountAgeSeconds < minAgeSeconds){
            long days = minAgeSeconds / 86400;
            throw new InvalidAccountException("Account too young");
        } else if (!json.getBoolean("has_verified_email")) {
            throw new InvalidAccountException("Account must have a verified e-mail");
        }
        return json.getString("name");
    }
}
 
开发者ID:xSke,项目名称:Pxls,代码行数:21,代码来源:RedditAuthService.java


注:本文中的com.mashape.unirest.http.HttpResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。