當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。