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

Requester.java 文件源码 项目:J-Cord 阅读 29 收藏 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 阅读 21 收藏 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;
}
GitHubSourceTaskTest.java 文件源码 项目:kafka-connect-github-source 阅读 23 收藏 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());
    }
}
UnirestForgeRockUserDao.java 文件源码 项目:dcsi 阅读 18 收藏 0 点赞 0 评论 0
@Override
public List<User> readUsers(String locatie) {
    try {
        HttpResponse<JsonNode> getResponse = Unirest
                .get("http://localhost:8080/openidm/managed/user?_prettyPrint=true&_queryId=query-all")
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .header("X-Requested-With", "Swagger-UI")
                .header("X-OpenIDM-Username", "openidm-admin")
                .header("X-OpenIDM-Password", "openidm-admin")
                .asJson();

        JSONObject body = getResponse.getBody().getObject();
        System.out.println(body.toString(4));
        JSONArray users = body.getJSONArray("result");
        List<User> result = new ArrayList<>();
        for (int i = 0, maxi = users.length(); i < maxi; i++) {
            result.add(toUser((JSONObject) users.get(i)));
        }
        return result;
    } catch (UnirestException e) {
        throw new RuntimeException("Wrapped checked exception.", e);
    }
}
CoinsHandler.java 文件源码 项目:botcoins-v1 阅读 19 收藏 0 点赞 0 评论 0
private void reloadCMCPrice() {
    try {
        HttpResponse<JsonNode> jsonResponse = Unirest.get("https://api.coinmarketcap.com/v1/ticker").asJson();
        JSONArray body = jsonResponse.getBody().getArray();
        synchronized (cmcCurrencies) {
            cmcCurrencies.clear();
            for (int i = 0; i < body.length(); i++) {
                JSONObject currency = body.getJSONObject(i);
                cmcCurrencies.add(new CurrencyData(currency.getString("name"), currency.getString("symbol"), !currency.isNull("price_btc") ? currency.getString("price_btc") : "0", !currency.isNull("price_usd") ? currency.getString("price_usd") : "0", !currency.isNull("market_cap_usd") ? currency.getString("market_cap_usd") : "0", !currency.isNull("percent_change_24h") ? currency.getString("percent_change_24h") : "0"));
            }
            CurrencyData btc = getCurrencyByCode("BTC");
            cmcCurrencies.add(new CurrencyData("American Dollar", "USD", 1 / btc.getUsdPrice(), 1, 0, 0, false));
            cmcCurrencies.add(new CurrencyData("Milli-Bitcoin", "mBTC", 0.001, btc.getUsdPrice() / 1000, btc.getMarketCap(), btc.getPctChange24h(), false));
            cmcCurrencies.add(new CurrencyData("Satoshi", "Sat", 0.00000001, btc.getUsdPrice() / 100000000, btc.getMarketCap(), btc.getPctChange24h(), false));
        }
        lastCoinMarketCapUpdate = System.currentTimeMillis();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
VulnDbParser.java 文件源码 项目:vulndb-data-mirror 阅读 16 收藏 0 点赞 0 评论 0
public <T> Results<T> parse(JsonNode jsonNode, Class<? extends ApiObject> apiObject) {
    LOGGER.debug("Parsing JSON node");

    final Results<T> results = new Results<>();
    final JSONObject root = jsonNode.getObject();
    results.setPage(root.getInt("current_page"));
    results.setTotal(root.getInt("total_entries"));
    results.setRawResults(jsonNode.toString());
    final JSONArray rso = root.getJSONArray("results");

    if (Product.class == apiObject) {
        results.setResults(parseProducts(rso));
    } else if (Vendor.class == apiObject) {
        results.setResults(parseVendors(rso));
    } else if (Version.class == apiObject) {
        results.setResults(parseVersions(rso));
    } else if (Vulnerability.class == apiObject) {
        results.setResults(parseVulnerabilities(rso));
    }
    return results;
}
GoogleAuthService.java 文件源码 项目:Pxls 阅读 60 收藏 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 阅读 21 收藏 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");
    }
}
VKAuthService.java 文件源码 项目:Pxls 阅读 20 收藏 0 点赞 0 评论 0
public String getIdentifier(String token) throws UnirestException, InvalidAccountException {
    HttpResponse<JsonNode> me = Unirest.get("https://api.vk.com/method/users.get?access_token=" + token)
            .header("User-Agent", "pxls.space")
            .asJson();
    JSONObject json = me.getBody().getObject();

    if (json.has("error")) {
        return null;
    } else {
        try {
            return Integer.toString(json.getJSONArray("response").getJSONObject(0).getInt("uid"));
        } catch (JSONException e) {
            return null;
        }
    }
}
TumblrAuthService.java 文件源码 项目:Pxls 阅读 19 收藏 0 点赞 0 评论 0
public String getIdentifier(String token) throws UnirestException, InvalidAccountException {
    String[] codes = token.split("\\|");
    HttpResponse<JsonNode> me = Unirest.get("https://api.tumblr.com/v2/user/info?" + getOauthRequest("https://api.tumblr.com/v2/user/info", "oauth_token="+codes[0], "oob", "GET", codes[1]))
            .header("User-Agent", "pxls.space")
            .asJson();
    JSONObject json = me.getBody().getObject();
    if (json.has("error")) {
        return null;
    } else {
        try {
            return json.getJSONObject("response").getJSONObject("user").getString("name");
        } catch (JSONException e) {
            return null;
        }
    }
}
DiscordAuthService.java 文件源码 项目:Pxls 阅读 25 收藏 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 阅读 26 收藏 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 阅读 25 收藏 0 点赞 0 评论 0
public String getToken(String code) throws UnirestException {
    HttpResponse<JsonNode> response = Unirest.post("https://www.reddit.com/api/v1/access_token")
            .header("User-Agent", "pxls.space")
            .field("grant_type", "authorization_code")
            .field("code", code)
            .field("redirect_uri", getCallbackUrl())
            .basicAuth(App.getConfig().getString("oauth.reddit.key"), App.getConfig().getString("oauth.reddit.secret"))
            .asJson();

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

    if (json.has("error")) {
        return null;
    } else {
        return json.getString("access_token");
    }
}
RedditAuthService.java 文件源码 项目:Pxls 阅读 21 收藏 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;
}
GDrvAPIOp.java 文件源码 项目:media_information_service 阅读 25 收藏 0 点赞 0 评论 0
private static void auxRetrieveAllFiles(List<String> lis,String auth, String link, String parents) throws IOException, UnirestException {
    HttpResponse<JsonNode> jsonResponse = Unirest.get(link).header("Authorization","Bearer "+auth).asJson();
    JSONObject jsonObject = new JSONObject(jsonResponse.getBody());
    JSONArray array = jsonObject.getJSONArray("array");
    for (int j=0;j<array.length();j++){
        JSONArray jarray=array.getJSONObject(j).getJSONArray("items");
        for(int i = 0; i < jarray.length(); i++)
        {
            if(jarray.getJSONObject(i).has("mimeType") && !jarray.getJSONObject(i).get("mimeType").equals("application/vnd.google-apps.folder")){
                String name= jarray.getJSONObject(i).getString("title");
                lis.add(jarray.getJSONObject(i).getString("title"));
            }
            else {
                if(jarray.getJSONObject(i).has("id")){
                    auxRetrieveAllFiles(lis,auth,"https://www.googleapis.com/drive/v2/files?includeTeamDriveItems=false&pageSize=500&q='"+jarray.getJSONObject(i).get("id")+"'%20in%20parents"+"&key="+ MISConfig.getGoogle_api(),parents);
                }
            }
        }
        if(array.getJSONObject(j).has("nextLink")){
            String next=array.getJSONObject(j).getString("nextLink");
            auxRetrieveAllFiles(lis,auth,next,parents);
        }
    }


}
HttpUtils.java 文件源码 项目:scalable-task-scheduler 阅读 21 收藏 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();
}
Util.java 文件源码 项目:graphql-codegen 阅读 22 收藏 0 点赞 0 评论 0
public static String fetchSchemaFromRemote(String url, String basicAuthUsername, String basicAuthPassword) {
    Map<String, String> bodyMap = new HashMap<>();
    bodyMap.put("query", introspectionQuery());
    bodyMap.put("variables", null);

    HttpRequestWithBody requestWithBody = Unirest.post(url)
            .header("Content-Type", "application/json")
            .header("accept", "application/json");

    // basic auth
    if (basicAuthUsername != null && basicAuthPassword != null) {
        requestWithBody.basicAuth(basicAuthUsername, basicAuthPassword);
    }

    // body
    RequestBodyEntity requestBodyEntity = requestWithBody.body(bodyMap);

    HttpResponse<JsonNode> jsonNodeHttpResponse;
    try {
        jsonNodeHttpResponse = requestBodyEntity.asJson();
    } catch (UnirestException e) {
        throw new RuntimeException(e);
    }

    return Util.convertStreamToString(jsonNodeHttpResponse.getRawBody(), "UTF-8");
}
RocketChatClientCallBuilder.java 文件源码 项目:rocket-chat-rest-client 阅读 18 收藏 0 点赞 0 评论 0
private void login() throws IOException {
    HttpResponse<JsonNode> loginResult;

    try {
        loginResult = Unirest.post(serverUrl + "v1/login").field("username", user).field("password", password).asJson();
    } catch (UnirestException e) {
        throw new IOException(e);
    }

    if (loginResult.getStatus() == 401)
        throw new IOException("The username and password provided are incorrect.");

    if (loginResult.getStatus() != 200)
        throw new IOException("The login failed with a result of: " + loginResult.getStatus());

    JSONObject data = loginResult.getBody().getObject().getJSONObject("data");
    this.authToken = data.getString("authToken");
    this.userId = data.getString("userId");
}
App.java 文件源码 项目:scouter-pulse 阅读 24 收藏 0 点赞 0 评论 0
private static int registerMetadata() throws UnirestException {
    JSONObject rootJson = new JSONObject();
    JSONObject objectJson = new JSONObject();
    objectJson.put("type", "website");
    objectJson.put("display", "Web");
    rootJson.put("object", objectJson);
    JSONArray counterArray = new JSONArray();
    rootJson.put("counters", counterArray);
JSONObject counterMap = new JSONObject();
counterArray.put(counterMap);
counterMap.put("name", "Time");
counterMap.put("unit", "ms");

    HttpResponse<JsonNode> response = Unirest.post("http://" + ip + ":" + port + "/register")
    .header("accept", "application/json")
    .header("content-type", "application/json")
    .body(rootJson).asJson();

    return response.getStatus();
  }
GabiaSmsService.java 文件源码 项目:hedwig 阅读 19 收藏 0 点赞 0 评论 0
@Override
public void sendCallBack(Sms sms, Object result) throws UnirestException {
    // TODO Auto-generated method stub
    for(int count = 0; count < 10; count++){
        try {
            HttpResponse<JsonNode> jsonResponse = Unirest.post(sms.getCallbackUrl())
                      .header("accept", "application/json")
                      .field("result", result)
                      .asJson();
            break;
        }
        catch (UnirestException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            if(count == 10){
                throw new UnirestException(e);
            }

            continue;
        }
    }

}
PlaylistService.java 文件源码 项目:spotify-pull-requests 阅读 25 收藏 0 点赞 0 评论 0
private static JSONObject createPlaylist(String spotifyId, String title, String authHeader) {
    HttpRequestWithBody http =
            Unirest.post("https://api.spotify.com/v1/users/" + spotifyId + "/playlists");

    try {
        HttpResponse<JsonNode> httpResponse = http
                .header("Content-Type", "application/json")
                .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36")
                .header("Authorization", authHeader)
                .body("{\"name\":\"" + title + "\", \"public\":true}")
                .asJson();

        JsonNode response = httpResponse.getBody();
        return response.getObject();
    } catch (Exception e) {
        e.printStackTrace();
        throw new WrapperException();
    }
}
Main.java 文件源码 项目:erp-demo 阅读 17 收藏 0 点赞 0 评论 0
public static void main(String[] args) throws Exception {
    try {
        JsonNode jsonData = new JsonNode("{}"); // json data without encrypt
        String keyFile = "/home/xuan/Downloads/449033.key";

        byte[] keyByte = EncryptUtils.getBytesFromFile(keyFile);
        Key key = EncryptUtils.restorePrivateKey(keyByte);

        HttpResponse<JsonNode> jsonResponse = Unirest
                .post(org_getall_url)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .field("eid", "449033")
                .field("nonce", UUID.randomUUID().toString())
                .field("data",
                        EncryptUtils.encryptWithEncodeBase64UTF8(
                                jsonData.toString(), key)).asJson();
        System.out.println(jsonResponse.getBody());
    } catch (UnirestException e) {
        e.printStackTrace();
    }
}
LoginHandler.java 文件源码 项目:DiscordBridge 阅读 28 收藏 0 点赞 0 评论 0
public static CommandResult otp(CommandSource commandSource, int code) {
    String ticket = MFA_TICKETS.remove(commandSource);
    if (ticket == null) {
        commandSource.sendMessage(Text.of(TextColors.RED, "No OTP auth queued!"));
        return CommandResult.empty();
    }
    try {
        HttpResponse<JsonNode> response = Unirest.post("https://discordapp.com/api/v6/auth/mfa/totp")
                .header("content-type", "application/json")
                .body(new JSONObject().put("code", String.format("%06d", code)).put("ticket", ticket))
                .asJson();
        if (response.getStatus() != 200) {
            commandSource.sendMessage(Text.of(TextColors.RED, "Wrong auth code! Retry with '/discord loginconfirm <email> <password>'"));
            return CommandResult.empty();
        }
        String token = response.getBody().getObject().getString("token");
        prepareHumanClient(Javacord.getApi(token, false), commandSource);
    } catch (UnirestException e) {
        e.printStackTrace();
        commandSource.sendMessage(Text.of(TextColors.RED, "Unexpected error!"));
        return CommandResult.empty();
    }

    return CommandResult.success();
}
KintoClientTest.java 文件源码 项目:kinto-http-java 阅读 20 收藏 0 点赞 0 评论 0
@Test(expected = KintoException.class)
public void testExecuteKintoError() throws UnirestException, KintoException, ClientException {
    // GIVEN a fake url
    String remote = "https://fake.kinto.url";
    // AND a kintoClient
    KintoClient kintoClient = new KintoClient(remote);
    // AND a httpResponse mock
    HttpResponse<JsonNode> response = mock(HttpResponse.class);
    doReturn(400).when(response).getStatus();
    doReturn("an error").when(response).getStatusText();
    // AND GetRequest mock
    GetRequest request = mock(GetRequest.class);
    doReturn(response).when(request).asJson();
    // WHEN calling execute
    kintoClient.execute(request);
    // THEN a KintoException is thrown
}
NgrokTunnel.java 文件源码 项目:ngrok-java-client 阅读 17 收藏 0 点赞 0 评论 0
public NgrokTunnel(String url, int port) throws UnirestException {
    this.name = UUID.randomUUID().toString();
    this.ngrokAddr = url;
    String payload = String.format(
            "{"
                + "\"addr\":\"%d\", "
                + "\"name\":\"%s\", "
                + "\"proto\":\"http\", "
                + "\"bind_tls\":\"false\"" +
            "}"
            , port, name);

    HttpResponse<JsonNode> jsonResponse = Unirest.post(ngrokAddr.concat("/api/tunnels"))
        .header("accept", "application/json")
        .header("Content-Type", "application/json; charset=utf8")
        .body(payload)
        .asJson();

    this.url = jsonResponse.getBody().getObject().getString("public_url");
}
UniRestCallback.java 文件源码 项目:brein-api-library-java 阅读 14 收藏 0 点赞 0 评论 0
@Override
public void completed(final HttpResponse<JsonNode> response) {
    final String strResponse = response.getBody().toString();
    final int status = response.getStatus();

    final BreinResult result;
    if (status == 200) {
        final Map<String, Object> mapResponse = this.engine.parseJson(strResponse);
        result = new BreinResult(mapResponse);
    } else {
        result = new BreinResult(strResponse, status);
    }

    if (this.callback != null) {
        this.callback.accept(result);
    }
}
KiteRequest.java 文件源码 项目:javakiteconnect 阅读 19 收藏 0 点赞 0 评论 0
/**
 * GET request using UniRest library.
 *
 * @param url is endpoint to which request has to be done.
 * @param params is data that has to be sent.
 * @return JSONObject returns json response.
 * @throws KiteException contains error message and error code inside.
 * @throws JSONException occurs when there is error while parsing data.
 */
public JSONObject getRequest(String url, Map<String, Object> params) throws KiteException, JSONException {

    try {
        if(KiteConnect.httpHost != null){
            Unirest.setProxy(KiteConnect.httpHost);
        }
        HttpResponse<JsonNode> response = Unirest.get(url).queryString(params)
                .header("accept", "application/json")
                .asJson();
        JsonNode body = response.getBody();
        JSONObject jsonObject = body.getObject();
        int code = response.getStatus();

        if (code == 200)
            return jsonObject;
        else
            throw dealWithKiteException(body, code);

    } catch (UnirestException e) {
       throw new KiteNoNetworkException("Connection error");
    }
}
KiteRequest.java 文件源码 项目:javakiteconnect 阅读 17 收藏 0 点赞 0 评论 0
/**
 * GET request using UniRest library without params.
 * @param url is endpoint to which request has to be done.
 * @return JSONObject returns json response.
 * @throws KiteException contains error message and error code inside.
 * @throws JSONException occurs when there is error while parsing data.
 */
public JSONObject getRequest(String url) throws KiteException, JSONException {

    try {
        if(KiteConnect.httpHost != null){
            Unirest.setProxy(KiteConnect.httpHost);
        }
        HttpResponse<JsonNode> response = Unirest.get(url)
                .header("accept", "application/json")
                .asJson();

        JsonNode body = response.getBody();
        JSONObject jsonObject = body.getObject();
        int code = response.getStatus();

        if (code == 200)
            return jsonObject;
        else
            throw dealWithKiteException(body, code);

    } catch (UnirestException e) {
        throw new KiteNoNetworkException("Connection error");
    }

}
OSMCities.java 文件源码 项目:RXJavaExercises 阅读 16 收藏 0 点赞 0 评论 0
private Observable<OSMCity> getCities(final String _search) {
    return Observable.create(new Observable.OnSubscribe<OSMCity>() {

        @Override
        public void call(Subscriber<? super OSMCity> arg0) {
            try {
                arg0.onStart();
                JsonNode json = Unirest
                        .get("https://nominatim.openstreetmap.org/search.php?format=json&q=" + _search)
                        .asJson()
                        .getBody();

                JSONArray array = json.getArray();

                for (int i = 0; i < array.length(); i++) {
                    arg0.onNext(new OSMCity(array.getJSONObject(i)));
                }
                arg0.onCompleted();

            } catch (UnirestException ex) {
                arg0.onError(ex);
            }
        }
    });
}


问题


面经


文章

微信
公众号

扫码关注公众号