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

TestBodyReading.java 文件源码 项目:javalin 阅读 24 收藏 0 点赞 0 评论 0
@Test
public void test_formParams_work() throws Exception {
    Javalin app = Javalin.create().port(0).start();
    app.before("/body-reader", ctx -> ctx.header("X-BEFORE", ctx.formParam("username")));
    app.post("/body-reader", ctx -> ctx.result(ctx.formParam("password")));
    app.after("/body-reader", ctx -> ctx.header("X-AFTER", ctx.formParam("repeat-password")));

    HttpResponse<String> response = Unirest
        .post("http://localhost:" + app.port() + "/body-reader")
        .body("username=some-user-name&password=password&repeat-password=password")
        .asString();

    assertThat(response.getHeaders().getFirst("X-BEFORE"), is("some-user-name"));
    assertThat(response.getBody(), is("password"));
    assertThat(response.getHeaders().getFirst("X-AFTER"), is("password"));
    app.stop();
}
Requester.java 文件源码 项目:J-Cord 阅读 29 收藏 0 点赞 0 评论 0
/**
 * Using the HttpMethod to return a http request.
 * @param params Parameters to be replaced.
 * @return The http request
 */
private HttpRequest requestHttp(Object... params) {
    String processedPath = processPath(params);

    HttpRequest request = null;
    switch (path.getMethod()) {
        case GET:
            request = Unirest.get(processedPath); break;
        case HEAD:
            request = Unirest.head(processedPath); break;
        case POST:
            request = Unirest.post(processedPath); break;
        case PUT:
            request = Unirest.put(processedPath); break;
        case PATCH:
            request = Unirest.patch(processedPath); break;
        case DELETE:
            request = Unirest.delete(processedPath); break;
        case OPTIONS:
            request = Unirest.options(processedPath); break;
    }
    processRequest(request);
    this.request = request;
    return request;
}
QuartzJob.java 文件源码 项目:async-engine 阅读 23 收藏 0 点赞 0 评论 0
public void execute(JobExecutionContext context) throws JobExecutionException {

        // Extract data from job
        Map<String, String> properties = (Map<String, String>) context.getMergedJobDataMap().get(Map.class.getCanonicalName());
        Set<String> taskIds = (Set<String>) context.getMergedJobDataMap().get(Task.class.getCanonicalName());

        taskIds.forEach(taskId -> {
            final String url = urlConverter(
                    DEFAULT_PROTOCOL,
                    properties.get(SERVER_IP),
                    properties.get(SERVER_PORT),
                    properties.get(SERVER_CONTEXT_PATH) + RETRY_PATH + "/" + taskId
            );

            try {
                final HttpResponse<String> httpResponse =
                        Unirest.get(url).asString();
            } catch (UnirestException e) {
                LOGGER.error("UnirestException", e);
            }
        });

    }
GDrvAPIOp.java 文件源码 项目:media_information_service 阅读 21 收藏 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;
}
Utils.java 文件源码 项目:MantaroRPG 阅读 20 收藏 0 点赞 0 评论 0
public static String paste(String toSend) {
    try {
        String pasteToken = Unirest.post("https://hastebin.com/documents")
            .header("User-Agent", "Mantaro")
            .header("Content-Type", "text/plain")
            .body(toSend)
            .asJson()
            .getBody()
            .getObject()
            .getString("key");
        return "https://hastebin.com/" + pasteToken;
    } catch (UnirestException e) {
        log.warn("Hastebin is being funny, huh? Cannot send or retrieve paste.", e);
        return "Bot threw ``" + e.getClass().getSimpleName() + "``" + " while trying to upload paste, check logs";
    }
}
JenkinsServiceApp.java 文件源码 项目:service-jenkins 阅读 24 收藏 0 点赞 0 评论 0
private synchronized void triggerJob() {
    try {
        logger.log(Level.INFO,"Starting Jenkins job: " + JOB_NAME);
        String result = null;
        switch(getJobType()) {
            case Parametrized:
                result = Unirest.post(JENKINS_URL + "/job/" + JOB_NAME + "/build").basicAuth(USER, API_TOKEN)
                        .field("json", getJSON())
                        .asBinary().getStatusText();
                break;
            case Normal:
                result = Unirest.post(JENKINS_URL + "/job/" + JOB_NAME + "/build").basicAuth(USER, API_TOKEN)
                        .asBinary().getStatusText();
                break;
        }
        logger.log(Level.INFO,"Done. Job '" + JOB_NAME + "' status: " + result);
    } catch (UnirestException e) {
        e.printStackTrace();
    }
}
Authentication.java 文件源码 项目:SugarOnRest 阅读 23 收藏 0 点赞 0 评论 0
/**
 * Logs out with the session identifier.
 *
 *  @param url REST API Url.
 *  @param sessionId Session identifier.
 */
public static void logout(String url, String sessionId) {
    try {
        Map<String, String> session = new LinkedHashMap<String, String>();
        session.put("user_name", sessionId);

        ObjectMapper mapper = new ObjectMapper();
        String jsonSessionData = mapper.writeValueAsString(session);

        Map<String, Object> request = new LinkedHashMap<String, Object>();
        request.put("method", "logout");
        request.put("input_type", "json");
        request.put("response_type", "json");
        request.put("rest_data", jsonSessionData);

        Unirest.post(url)
                .fields(request)
                .asString();
    }
    catch (Exception exception) {
    }
}
GoogleAuthService.java 文件源码 项目:Pxls 阅读 29 收藏 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 阅读 28 收藏 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 阅读 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 阅读 21 收藏 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 阅读 21 收藏 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 阅读 20 收藏 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");
    }
}
Deployment.java 文件源码 项目:SKIL_Examples 阅读 24 收藏 0 点赞 0 评论 0
public JSONArray getAllDeployments() {
    JSONArray deployments = new JSONArray();

    try {
        deployments =
                Unirest.get(MessageFormat.format("http://{0}:{1}/deployments", host, port))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .asJson()
                        .getBody().getArray();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return deployments;
}
Deployment.java 文件源码 项目:SKIL_Examples 阅读 28 收藏 0 点赞 0 评论 0
public JSONObject getDeploymentById(int id) {
    JSONObject deployment = new JSONObject();

    try {
        deployment =
                Unirest.get(MessageFormat.format("http://{0}:{1}/deployment/{2}", host, port, id))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return deployment;
}
Deployment.java 文件源码 项目:SKIL_Examples 阅读 25 收藏 0 点赞 0 评论 0
public JSONObject addDeployment(String name) {
    JSONObject addedDeployment = new JSONObject();

    try {
        addedDeployment =
                Unirest.post(MessageFormat.format("http://{0}:{1}/deployment", host, port))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject() //Using this because the field functions couldn't get translated to an acceptable json
                                .put("name", name)
                                .toString())
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return addedDeployment;
}
Deployment.java 文件源码 项目:SKIL_Examples 阅读 28 收藏 0 点赞 0 评论 0
public JSONArray getModelsForDeployment(int id) {
    JSONArray allModelsOfDeployment = new JSONArray();

    try {
        allModelsOfDeployment =
                Unirest.get(MessageFormat.format("http://{0}:{1}/deployment/{2}/models", host, port, id))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .asJson()
                        .getBody().getArray();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return allModelsOfDeployment;
}
Authorization.java 文件源码 项目:SKIL_Examples 阅读 30 收藏 0 点赞 0 评论 0
public String getAuthToken(String userId, String password) {
    String authToken = null;

    try {
        authToken =
                Unirest.post(MessageFormat.format("http://{0}:{1}/login", host, port))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject() //Using this because the field functions couldn't get translated to an acceptable json
                                .put("userId", userId)
                                .put("password", password)
                                .toString())
                        .asJson()
                        .getBody().getObject().getString("token");
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return authToken;
}
KNN.java 文件源码 项目:SKIL_Examples 阅读 22 收藏 0 点赞 0 评论 0
public JSONObject addKNN(String name, String fileLocation, int scale, String uri) {
    JSONObject knn = new JSONObject();

    try {
        List<String> uriList = new ArrayList<String>();
        uriList.add(uri);

        knn =
                Unirest.post(MessageFormat.format("http://{0}:{1}/deployment/{2}/model", host, port, deploymentID))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject()
                                .put("name", name)
                                .put("modelType", "knn")
                                .put("fileLocation", fileLocation)
                                .put("scale", scale)
                                .put("uri", uriList)
                                .toString())
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return knn;
}
TestBodyReading.java 文件源码 项目:javalin 阅读 23 收藏 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();
}
RecordingSystem.java 文件源码 项目:tdl-runner-scala 阅读 22 收藏 0 点赞 0 评论 0
static void notifyEvent(String lastFetchedRound, String shortName) {
    System.out.printf("Notify round \"%s\", event \"%s\"%n", lastFetchedRound, shortName);

    if (!isRecordingRequired()) {
        return;
    }

    try {
        HttpResponse<String> stringHttpResponse = Unirest.post(RECORDING_SYSTEM_ENDPOINT + "/notify")
                .body(lastFetchedRound+"/"+shortName)
                .asString();
        if (stringHttpResponse.getStatus() != 200) {
            System.err.println("Recording system returned code: "+stringHttpResponse.getStatus());
            return;
        }

        if (!stringHttpResponse.getBody().startsWith("ACK")) {
            System.err.println("Recording system returned body: "+stringHttpResponse.getStatus());
        }
    } catch (UnirestException e) {
        System.err.println("Could not reach recording system: " + e.getMessage());
    }
}
Model.java 文件源码 项目:SKIL_Examples 阅读 29 收藏 0 点赞 0 评论 0
public JSONObject addModel(String name, String fileLocation, int scale, String uri) {
    JSONObject model = new JSONObject();

    try {
        List<String> uriList = new ArrayList<String>();
        uriList.add(uri);

        model =
                Unirest.post(MessageFormat.format("http://{0}:{1}/deployment/{2}/model", host, port, deploymentID))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject()
                                .put("name", name)
                                .put("modelType", "model")
                                .put("fileLocation", fileLocation)
                                .put("scale", scale)
                                .put("uri", uriList)
                                .toString())
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return model;
}
Model.java 文件源码 项目:SKIL_Examples 阅读 25 收藏 0 点赞 0 评论 0
public JSONObject reimportModel(int modelID, String name, String fileLocation) {
    JSONObject model = new JSONObject();

    try {
        model =
                Unirest.post(MessageFormat.format("http://{0}:{1}/deployment/{2}/model/{3}", host, port, deploymentID, modelID))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject()
                                .put("name", name)
                                .put("modelType", "model")
                                .put("fileLocation", fileLocation)
                                .toString())
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return model;
}
Model.java 文件源码 项目:SKIL_Examples 阅读 27 收藏 0 点赞 0 评论 0
public JSONObject deleteModel(int modelID) {
    JSONObject model = new JSONObject();

    try {
        model =
                Unirest.delete(MessageFormat.format("http://{0}:{1}/deployment/{2}/model/{3}", host, port, deploymentID, modelID))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return model;
}
Model.java 文件源码 项目:SKIL_Examples 阅读 27 收藏 0 点赞 0 评论 0
public JSONObject setModelState(int modelID, String state) {
    JSONObject model = new JSONObject();

    try {
        model =
                Unirest.delete(MessageFormat.format("http://{0}:{1}/deployment/{2}/model/{3}/state", host, port, deploymentID, modelID))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject()
                                .put("name", state)
                                .toString())
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return model;
}
Transform.java 文件源码 项目:SKIL_Examples 阅读 29 收藏 0 点赞 0 评论 0
public JSONObject addTransform(String name, String fileLocation, int scale, String uri) {
    JSONObject transform = new JSONObject();

    try {
        List<String> uriList = new ArrayList<String>();
        uriList.add(uri);

        transform =
                Unirest.post(MessageFormat.format("http://{0}:{1}/deployment/{2}/model", host, port, deploymentID))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject()
                                .put("name", name)
                                .put("modelType", "transform")
                                .put("fileLocation", fileLocation)
                                .put("scale", scale)
                                .put("uri", uriList)
                                .toString())
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return transform;
}
Transform.java 文件源码 项目:SKIL_Examples 阅读 29 收藏 0 点赞 0 评论 0
public JSONObject setTransformState(int transformID, String state) {
    JSONObject transform = new JSONObject();

    try {
        transform =
                Unirest.delete(MessageFormat.format("http://{0}:{1}/deployment/{2}/model/{3}/state", host, port, deploymentID, transformID))
                        .header("accept", "application/json")
                        .header("Content-Type", "application/json")
                        .body(new JSONObject()
                                .put("name", state)
                                .toString())
                        .asJson()
                        .getBody().getObject();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return transform;
}
DownloadFactory.java 文件源码 项目:minebox 阅读 22 收藏 0 点赞 0 评论 0
protected InputStream downloadLatestMetadataZip(String token) throws UnirestException {
    final HttpResponse<InputStream> response = Unirest.get(metadataUrl + "file/latestMeta")
            .header("X-Auth-Token", token)
            .asBinary();
    if (response.getStatus() == 404) return null;
    return response.getBody();
}
RemoteTokenService.java 文件源码 项目:minebox 阅读 22 收藏 0 点赞 0 评论 0
public Optional<String> getToken() {
        final ListenableFuture<String> masterPassword = encyptionKeyProvider.getMasterPassword();
        if (!masterPassword.isDone()) {
            return Optional.empty();
        }
        final String key = encyptionKeyProvider.getImmediatePassword();
        final String s = key + " meta";
        final ECKey privKey = ECKey.fromPrivate(Sha256Hash.twiceOf(s.getBytes(Charsets.UTF_8)).getBytes());

/*
        @POST
        @Path("/token")
        @Produces(MediaType.APPLICATION_OCTET_STREAM)
        public Response createToken(@QueryParam("timestamp") Long nonce, @QueryParam("signature") String signature) {
*/

//        }
        final long timeStamp = Instant.now().toEpochMilli();
        try {
            final String url = rootPath + "auth/token";
            final HttpResponse<String> token = Unirest.post(url)
                    .queryString("timestamp", timeStamp)
                    .queryString("signature", privKey.signMessage(String.valueOf(timeStamp)))
                    .asString();
            if (token.getStatus() != 200) {
                return Optional.empty();
            }
            return Optional.of(token.getBody());
        } catch (UnirestException e) {
            LOGGER.error("exception from remote service when trying to get token", e);
            return Optional.empty();
        }

    }


问题


面经


文章

微信
公众号

扫码关注公众号