java类com.mashape.unirest.http.HttpResponse的实例源码

Requester.java 文件源码 项目:J-Cord 阅读 28 收藏 0 点赞 0 评论 0
/**
 * @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;
}
Requester.java 文件源码 项目:J-Cord 阅读 30 收藏 0 点赞 0 评论 0
/**
 * @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;
}
HttpUtils.java 文件源码 项目:scalable-task-scheduler 阅读 27 收藏 0 点赞 0 评论 0
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();
}
SiaUtil.java 文件源码 项目:minebox 阅读 28 收藏 0 点赞 0 评论 0
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;
    }
GitHubSourceTaskTest.java 文件源码 项目:kafka-connect-github-source 阅读 25 收藏 0 点赞 0 评论 0
@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());
    }
}
TestFileUpload.java 文件源码 项目:javalin 阅读 23 收藏 0 点赞 0 评论 0
@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();
}
Table.java 文件源码 项目:airtable.java 阅读 26 收藏 0 点赞 0 评论 0
/**
 * 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;
}
TestBodyReading.java 文件源码 项目:javalin 阅读 24 收藏 0 点赞 0 评论 0
@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();
}
HGraphQLService.java 文件源码 项目:hypergraphql 阅读 25 收藏 0 点赞 0 评论 0
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;
    }
GoogleAuthService.java 文件源码 项目:Pxls 阅读 24 收藏 0 点赞 0 评论 0
@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");
    }
}
VKAuthService.java 文件源码 项目:Pxls 阅读 30 收藏 0 点赞 0 评论 0
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");
    }
}
TumblrAuthService.java 文件源码 项目:Pxls 阅读 23 收藏 0 点赞 0 评论 0
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 "/";
    }
}
DiscordAuthService.java 文件源码 项目:Pxls 阅读 26 收藏 0 点赞 0 评论 0
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");
    }
}
DiscordAuthService.java 文件源码 项目:Pxls 阅读 22 收藏 0 点赞 0 评论 0
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");
    }
}
RedditAuthService.java 文件源码 项目:Pxls 阅读 27 收藏 0 点赞 0 评论 0
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");
    }
}
GDrvAPIOp.java 文件源码 项目:media_information_service 阅读 26 收藏 0 点赞 0 评论 0
public static List<String> retrieveAllFiles(String auth, String folder) throws IOException, UnirestException {
    List<String> lis= new LinkedList<String>();
    HttpResponse<JsonNode> jsonResponse = Unirest.get("https://www.googleapis.com/drive/v2/files/root/children?q=title='"+folder+"'").header("Authorization","Bearer "+auth).asJson();
    JSONObject jsonObject= new JSONObject(jsonResponse.getBody());
    JSONArray array = jsonObject.getJSONArray("array");
    for(int i=0;i<array.length();i++){
        JSONArray jarray=array.getJSONObject(i).getJSONArray("items");
        int j=jarray.length();
        while(j>0){
            String id=jarray.getJSONObject(0).getString("id");
            auxRetrieveAllFiles(lis,auth,"https://www.googleapis.com/drive/v2/files?includeTeamDriveItems=false&pageSize=500&q='"+id+"'%20in%20parents"+"&key="+ MISConfig.getGoogle_api(),id);
            j--;
        }

    }
    return lis;
}
TestBodyReading.java 文件源码 项目:javalin 阅读 27 收藏 0 点赞 0 评论 0
@Test
public void test_bodyReader_reverse() throws Exception {
    Javalin app = Javalin.create().port(0).start();
    app.before("/body-reader", ctx -> ctx.header("X-BEFORE", ctx.queryParam("qp") + ctx.body()));
    app.post("/body-reader", ctx -> ctx.result(ctx.queryParam("qp") + ctx.body()));
    app.after("/body-reader", ctx -> ctx.header("X-AFTER", ctx.queryParam("qp") + ctx.body()));

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

    assertThat(response.getHeaders().getFirst("X-BEFORE"), is("queryparambody"));
    assertThat(response.getBody(), is("queryparambody"));
    assertThat(response.getHeaders().getFirst("X-AFTER"), is("queryparambody"));
    app.stop();
}
Requester.java 文件源码 项目:J-Cord 阅读 23 收藏 0 点赞 0 评论 0
/**
 * Performs requests
 * @return HttpCode, the response status
 */
public HttpCode performRequest() {
    try {
        HttpResponse<JsonNode> response = request.asJson();
        checkRateLimit(response);
        handleErrorCode(response);
        JsonNode node = response.getBody();
        if (node != null && !node.isArray()) {
            handleErrorResponse(node.getObject());
        }
        return HttpCode.getByKey(response.getStatus());
    } catch (UnirestException e) {
        throw new RuntimeException("Fail to perform http request!");
    }
}
Requester.java 文件源码 项目:J-Cord 阅读 19 收藏 0 点赞 0 评论 0
@SuppressWarnings("unchecked")
private void handleErrorCode(HttpResponse response) {
    HttpCode error = HttpCode.getByKey(response.getStatus());
    if (error.isServerError() || error.isFailure()) {
        if (error.equals(HttpCode.TOO_MANY_REQUESTS)) { // Rate limited
            checkRateLimit(response);
        } else {
            throw new HttpErrorException(error);
        }
    } else if (error == HttpCode.UNKNOWN){
        throw new HttpErrorException(response.getStatus(), response.getStatusText());
    }
}
TestFilters.java 文件源码 项目:javalin 阅读 29 收藏 0 点赞 0 评论 0
@Test
public void test_justFilters_is404() throws Exception {
    Handler emptyHandler = ctx -> {
    };
    app.before(emptyHandler);
    app.after(emptyHandler);
    HttpResponse<String> response = call(HttpMethod.GET, "/hello");
    assertThat(response.getStatus(), is(404));
    assertThat(response.getBody(), is("Not found"));
}
TestExceptionMapper.java 文件源码 项目:javalin 阅读 28 收藏 0 点赞 0 评论 0
@Test
public void test_mappedException_isHandled() throws Exception {
    app.get("/mapped-exception", ctx -> {
        throw new Exception();
    }).exception(Exception.class, (e, ctx) -> ctx.result("It's been handled."));
    HttpResponse<String> response = GET_asString("/mapped-exception");
    assertThat(response.getBody(), is("It's been handled."));
    assertThat(response.getStatus(), is(200));
}
StrawpollObject.java 文件源码 项目:momo-2 阅读 26 收藏 0 点赞 0 评论 0
/**
 * Create the poll as represented by this object
 * @return ID of the created poll
 * @throws IOException Something bad happened when accessing the resource
 */
public int createPoll() throws UnirestException {
    HttpResponse<JsonNode> jsonResponse = Unirest.post(BASE_API)
            .header("Content-Type", "application/json")
            .body((new Gson()).toJson(this))
            .asJson();
    return jsonResponse.getBody().getObject().getInt("id");
}
SiaUtil.java 文件源码 项目:minebox 阅读 23 收藏 0 点赞 0 评论 0
private static boolean checkErrorFragment(HttpResponse<String> reply, String fragment) {
    if (reply == null) {
        throw new RuntimeException("reply was null!. checking for fragment: " + fragment);
    }
    if (statusGood(reply)) {
        return false;
    }
    final String body = reply.getBody();
    if (body == null) {
        throw new RuntimeException("replybody was null! checking for fragment: " + fragment);
    }
    return body.contains(fragment);
}
TestHaltException.java 文件源码 项目:javalin 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void test_haltBeforeWildcard_works() throws Exception {
    app.before("/admin/*", ctx -> {
        throw new HaltException(401);
    });
    app.get("/admin/protected", ctx -> ctx.result("Protected resource"));
    HttpResponse<String> response = call(HttpMethod.GET, "/admin/protected");
    assertThat(response.getStatus(), is(401));
    assertThat(response.getBody(), not("Protected resource"));
}
SiaUtil.java 文件源码 项目:minebox 阅读 33 收藏 0 点赞 0 评论 0
private HttpResponse<String> siaCommand(SiaCommand command, ImmutableMap<String, Object> params, String... extraCommand) {
    try {
        final HttpRequest httpRequest = command.unirest(path, extraCommand)
                .header("User-Agent", "Sia-Agent")
                .queryString(params);
        return httpRequest.asString();
    } catch (UnirestException e) {
        throw new NoConnectException(e);
    }
}
ChallengeServerClient.java 文件源码 项目:tdl-runner-scala 阅读 26 收藏 0 点赞 0 评论 0
String sendAction(String action) throws
        ClientErrorException, ServerErrorException, OtherCommunicationException {
    try {
        String encodedPath = URLEncoder.encode(this.journeyId, "UTF-8");
        String url = String.format("http://%s:%d/action/%s/%s", this.url, port, action, encodedPath);
        HttpResponse<String> response =  Unirest.post(url)
                .header("Accept", this.acceptHeader)
                .header("Accept-Charset", "UTF-8")
                .asString();
        ensureStatusOk(response);
        return response.getBody();
    } catch (UnirestException | UnsupportedEncodingException e ) {
        throw new OtherCommunicationException("Could not perform POST request",e);
    }
}
SiaUtil.java 文件源码 项目:minebox 阅读 29 收藏 0 点赞 0 评论 0
private static boolean statusGood(HttpResponse<String> response) {
    if (response == null) {
        return false;
    }
    final int status = response.getStatus();
    return status >= 200 && status < 300;
}
TestCors.java 文件源码 项目:javalin 阅读 23 收藏 0 点赞 0 评论 0
@Test
public void test_enableCorsForSpecificOrigins() throws Exception {
    Javalin app1 = Javalin.create().port(0).enableCorsForOrigin("origin-1", "referer-1").start();
    app1.get("/", ctx -> ctx.result("Hello"));
    HttpResponse<String> response = Unirest.get("http://localhost:" + app1.port() + "/").asString();
    assertThat(response.getHeaders().get("Access-Control-Allow-Origin"), is(nullValue()));
    response = Unirest.get("http://localhost:" + app1.port() + "/").header("Origin", "origin-1").asString();
    assertThat(response.getHeaders().get("Access-Control-Allow-Origin").get(0), is("origin-1"));
    response = Unirest.get("http://localhost:" + app1.port() + "/").header("Referer", "referer-1").asString();
    assertThat(response.getHeaders().get("Access-Control-Allow-Origin").get(0), is("referer-1"));
    app1.stop();
}
ChromaClient.java 文件源码 项目:RazerChromaRESTClient 阅读 22 收藏 0 点赞 0 评论 0
/**
 * Un-initializes this client
 *
 * @return {@link Result}
 * @throws UnirestException
 */
public Result unInit() throws UnirestException {
    checkInitialized();
    HttpResponse<ResponseResult> response = Unirest
            .delete(this.session.getUri())
            .asObject(ResponseResult.class);
    this.session = null;
    this.heartbeatThread = null;
    return Result.forCode(response.getBody().getResult());
}
Gephi.java 文件源码 项目:exportJanusGraphToGephi 阅读 19 收藏 0 点赞 0 评论 0
public void updateGraph(String type, JSONObject node) {

        JSONObject jsonObj = new JSONObject();
        jsonObj.put(type, node);

        //System.out.println(jsonObj.toString());
        try {
            HttpResponse<String> response = Unirest.post(url + "?operation=updateGraph")
                    .header("content-type", "application/json")
                    .header("cache-control", "no-cache")
                    .body(jsonObj.toString())
                    .asString();
            Integer i = 0;
            if (type.equals("ae")) {
                this.ECount++;
                i = this.ECount;
            }
            if (type.equals("an")) {
                this.VCount++;
                i = this.VCount;
            }
            System.out.println(i + " " + response.getStatus() + " " + response.getStatusText() + " " + response.getBody());
        } catch(UnirestException e) {
            e.printStackTrace();
        }

    }


问题


面经


文章

微信
公众号

扫码关注公众号