Java 类com.mashape.unirest.http.exceptions.UnirestException 实例源码

项目:media_information_service    文件:MainController.java   
@PostMapping("/result_book")
public String mediaBookSubmit(@ModelAttribute Media media, Model model, HttpServletRequest request ) {
    //System.out.println(media.getISBN());
    LinkedList<BookInfo> a = null;
    String maxResult= media.getMaxResult();
    if (maxResult.equals("")) maxResult="10";
    if (media.getTitle().trim().equals("") && media.getISBN().trim().equals("")) return "media_book";
    else if (media.getTitle().equals("") && media.getISBN().length()!=13) return "media_book";
    try {
        a = APIOperations.bookGetInfo(media.getTitle().trim(), media.getISBN().trim(), maxResult, media.getOrderBy());
    } catch (UnirestException e) {
        e.printStackTrace();
        return String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR);

    }
    RabbitSend.sendMediaRequest(media.getTitle(),"Book",request);
    if (a.size()==0) return "no_result";
    model.addAttribute("mediaList", a);
    return "result_book";
}
项目:J-Cord    文件:Requester.java   
/**
 * @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;
}
项目:SKIL_Examples    文件:Transform.java   
public JSONObject deleteTransform(int transformID) {
    JSONObject transform = new JSONObject();

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

    return transform;
}
项目:SKIL_Examples    文件:Model.java   
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;
}
项目:media_information_service    文件:GDrvAPIOp.java   
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;
}
项目:SKIL_Examples    文件:Transform.java   
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;
}
项目:SKIL_Examples    文件:Authorization.java   
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;
}
项目:Pxls    文件:RedditAuthService.java   
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");
    }
}
项目:SKIL_Examples    文件:Model.java   
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;
}
项目:SKIL_Examples    文件:KNN.java   
public JSONObject deleteKNN(int knnID) {
    JSONObject knn = new JSONObject();

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

    return knn;
}
项目:Pxls    文件:VKAuthService.java   
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;
        }
    }
}
项目:eadlsync    文件:CommandTest.java   
@Before
public void methodSetUp() throws IOException, UnirestException {
    // one commit with four decisions is always available and we have the same decisions as eadls
    // in our code repo
    seRepoTestServer.createRepository();
    seRepoTestServer.createCommit(getBasicDecisionsAsSeItemsWithContent(), CommitMode.ADD_UPDATE);

    DecisionSourceMapping.clear();
    Path code = codeBase.getRoot().toPath();
    codeRepoMock = new CodeRepoMock(code);
    codeRepoMock.createClassesForEadls(getBasicDecisionsAsEadl());

    commander.parse(InitCommand.NAME, "-u", seRepoTestServer.LOCALHOST_SEREPO, "-p", TEST_REPO,
            "-s", code.toString());
    INIT_COMMAND.initialize();
}
项目:media_information_service    文件:GDrvAPIOp.java   
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);
        }
    }


}
项目:SKIL_Examples    文件:Deployment.java   
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;
}
项目:momo-2    文件:Strawpoll.java   
@Override
public void finish() {
    String title = (String) super.getResponses().get(0);
    if(title.length() > 400) {
        super.sendMessage("Error: Title length cannot be greater than 400 characters");
        super.exit();
    }
    boolean multi = (boolean) super.getResponses().get(1);
    String[] options = super.getResponses().subList(2, super.getResponses().size())
            .toArray(new String[super.getResponses().size() - 2]);
    if(options.length < 2 || options.length > 30) {
        super.sendMessage("Error: You must have between 2 and 30 options (inclusive)");
        super.exit();
    }
    StrawpollObject poll = new StrawpollObject(title, multi, options);
    try {
        super.sendMessage("http://www.strawpoll.me/" + poll.createPoll());
    } catch (UnirestException e) {
        super.sendMessage("Sorry, something went wrong creating your Strawpoll - Might be over my limits!");
        e.printStackTrace();
    }
    super.exit();
}
项目:LiveboxFibraExtractor    文件:LiveboxFibraExtractor.java   
public static void getAllSIPData() throws UnirestException, Exception{
    LiveboxAPI.INSTANCE.getWAN();
    System.out.println(LiveboxAPI.INSTANCE.getMAC());

    JSONArray lines = LiveboxAPI.getLines();
    //System.out.println(lines.toString());
    for(int i=0;i<lines.length();i++){
        JSONObject l = lines.getJSONObject(i);
        //System.out.println(l.getString("name"));
        if(l.getString("status").equals("Up"))
        {
            JSONObject lineInfo = LiveboxAPI.getLine(l.getString("name"));
            //System.out.println(lineInfo.toString());

            System.out.println("userId: "+ lineInfo.getString("name"));
            System.out.println("authPassword: "+ lineInfo.getString("authPassword"));
            System.out.println("authId: "+ lineInfo.getString("authUserName"));
        }
    }

    JSONObject sip = LiveboxAPI.getSIP();
    System.out.println("userAgentDomain: "+ sip.getString("userAgentDomain"));
    System.out.println("outboundProxyServer: "+ sip.getString("outboundProxyServer"));
    System.out.println("outboundProxyServerPort: "+ sip.getInt("outboundProxyServerPort"));
}
项目:drinkwater-java    文件:ServiceManagementRestTest.java   
@Test
public void shouldStartAndStopService() throws UnirestException {
    httpPostRequestString(MANAGEMENT_API_ENDPOINT + "/stopservice?serviceName=test", "")
            .expectsBody("Service test stopped")
            .expectsStatus(200);

    httpGetString(MANAGEMENT_API_ENDPOINT + "/ServiceState?serviceName=test")
            .expectsBody("Stopped")
            .expectsStatus(200);

    httpPostRequestString(MANAGEMENT_API_ENDPOINT + "/startservice?serviceName=test", "")
            .expectsBody("Service test started")
            .expectsStatus(200);

    httpGetString(MANAGEMENT_API_ENDPOINT + "/ServiceState?serviceName=test")
            .expectsBody("Up")
            .expectsStatus(200);

}
项目:SKIL_Examples    文件:Deployment.java   
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;
}
项目:messages-java-sdk    文件:UnirestClient.java   
/**
 * Publishes success or failure result as HttpResponse from a HttpRequest
 * @param   response    The http response to publish
 * @param   context     The user specified context object
 * @param   completionBlock     The success and failure code block reference to invoke the delegate
 * @param   uniException       The reported errors for getting the http response
 */
protected static void publishResponse (com.mashape.unirest.http.HttpResponse<?> response,
                             HttpRequest request, APICallBack<HttpResponse> completionBlock, UnirestException uniException)
{
    HttpResponse httpResponse = ((response == null) ? null : UnirestClient.convertResponse(response));
    HttpContext context = new HttpContext(request, httpResponse);

    //if there are no errors, try to convert to our internal format
    if(uniException == null && httpResponse != null)
    {            
        completionBlock.onSuccess(context, httpResponse);
    }
    else
    {
        Throwable innerException = uniException.getCause();
        completionBlock.onFailure(context, new APIException(innerException.getMessage()));
    }
}
项目:hypergraphql    文件:HGraphQLService.java   
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;
    }
项目:dcsi    文件:UnirestForgeRockUserDao.java   
@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);
    }
}
项目:Pxls    文件:DiscordAuthService.java   
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");
    }
}
项目:Pxls    文件:TumblrAuthService.java   
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 "/";
    }
}
项目:service-jenkins    文件:JenkinsServiceApp.java   
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();
    }
}
项目:async-engine    文件:QuartzJob.java   
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);
            }
        });

    }
项目:Pxls    文件:VKAuthService.java   
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");
    }
}
项目:GensokyoBot    文件:DiscordUtil.java   
public static User getUserFromBearer(JDA jda, String token) {
    try {
        JSONObject user =  Unirest.get(Requester.DISCORD_API_PREFIX + "/users/@me")
                .header("Authorization", "Bearer " + token)
                .header("User-agent", USER_AGENT)
                .asJson()
                .getBody()
                .getObject();

        if(user.has("id")){
            return jda.retrieveUserById(user.getString("id")).complete(true);
        }
    } catch (UnirestException | RateLimitedException ignored) {}

    return null;
}
项目:Pxls    文件:RedditAuthService.java   
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");
    }
}
项目:Pxls    文件:GoogleAuthService.java   
@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");
    }
}
项目:J-Cord    文件:Requester.java   
/**
 * 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!");
    }
}
项目:nifi-dataminded-bundle    文件:UpdateAttributeREST.java   
@Override
public void onTrigger(ProcessContext processContext, ProcessSession processSession) throws ProcessException {

    // Get flowfile
    FlowFile flowFile = processSession.get();
    if (flowFile == null) {
        return;
    }

    try {

        // Get filename of flowFile
        String fileName = flowFile.getAttribute(CoreAttributes.FILENAME.key());

        // Invoke REST service with filename as parameter (For now parameter is just '1')
        String restEndpoint = processContext.getProperty(REST_ENDPOINT).getValue();
        JSONObject jsonResult = Unirest.get(restEndpoint)
                .header("accept", "application/json")
                .asJson()
                .getBody()
                .getObject();

        // Add attributes to flowfile based on REST call
        Map<String, String> newAttributes = new HashMap<>();
        newAttributes.put(ATT_ACCOUNT_NAME, jsonResult.getString("name"));
        newAttributes.put(ATT_ACCOUNT_USERNAME, jsonResult.getString("username"));
        FlowFile updatedFlowFile = processSession.putAllAttributes(flowFile, newAttributes);

        // Transfer flowfile to success state
        processSession.transfer(updatedFlowFile, REL_SUCCESS);

    } catch (UnirestException e) {
        processSession.transfer(flowFile, REL_FAILURE);
        throw new ProcessException(e);
    }
}
项目:RazerChromaRESTClient    文件:ChromaClient.java   
/**
 * Creates an effect
 *
 * @param effect the {@link EffectAbstract}
 * @return the {@link EffectId} to be used when setting the effect
 * @throws UnirestException
 */
public EffectId createEffect(EffectAbstract effect) throws UnirestException {
    System.out.println("createEffect POST " + effect.getTarget().getRoute());
    System.out.println(new Gson().toJson(effect));
    checkInitialized();
    HttpResponse<EffectId> response = Unirest
            .post(this.session.getUri() + effect.getTarget().getRoute())
            .body(effect)
            .asObject(EffectId.class);
    return response.getBody();
}
项目:minebox    文件:SiaUtil.java   
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);
    }
}
项目:exportJanusGraphToGephi    文件:Gephi.java   
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();
        }

    }
项目:exportJanusGraphToGephi    文件:Gephi.java   
public static void updateGraphTest() {

        //System.out.println(jsonObj.toString());

        try {
            HttpResponse<JsonNode> response = Unirest.post(url + "?operation=updateGraph")
                    .header("content-type", "application/json")
                    .header("cache-control", "no-cache")
                    .body("{\"an\":{\"520248\":{\"id\":520248,\"label\":\"artist\"}}}")
                    .asJson();
            System.out.println(response.getBody());
        } catch(UnirestException e) {
            e.printStackTrace();
        }
    }
项目:JPastee    文件:JPastee.java   
/**
 * Lists the available syntaxes from the server.
 *
 * @see <a href="https://pastee.github.io/docs/#list-syntaxes">Pastee Docs: List Syntaxes</a>
 * @return the response of the request
 */
public SyntaxesResponse listSyntaxes() {
    final String route = "/syntaxes";

    try {
        return new SyntaxesResponse(get(route).getBody().getObject());
    } catch(UnirestException e) {
        return new SyntaxesResponse(e);
    }
}
项目:Pxls    文件:PacketHandler.java   
private void handleCaptcha(WebSocketChannel channel, User user, ClientCaptcha cc) {
    if (!user.isFlaggedForCaptcha()) return;
    if (user.isBanned()) return;

    Unirest
            .post("https://www.google.com/recaptcha/api/siteverify")
            .field("secret", App.getConfig().getString("captcha.secret"))
            .field("response", cc.getToken())
            //.field("remoteip", "null")
            .asJsonAsync(new Callback<JsonNode>() {
                @Override
                public void completed(HttpResponse<JsonNode> response) {
                    JsonNode body = response.getBody();

                    String hostname = App.getConfig().getString("host");

                    boolean success = body.getObject().getBoolean("success") && body.getObject().getString("hostname").equals(hostname);
                    if (success) {
                        user.validateCaptcha();
                    }

                    server.send(channel, new ServerCaptchaStatus(success));
                }

                @Override
                public void failed(UnirestException e) {

                }

                @Override
                public void cancelled() {

                }
            });
}
项目:eadlsync    文件:CodeRepo.java   
@Override
public String commit(User user, String message, boolean isForcing) throws EADLSyncException, IOException, UnirestException {
    diffManager = initDiff(latestCommitId());
    if (!diffManager.hasRemoteDiff() || isForcing) {
        if (diffManager.hasLocalDiff()) {
            diffManager.applyLocalDiff();
            return YStatementSeItemHelper.commitYStatement(user, message, diffManager.getCurrentDecisions(), baseUrl, project);
        } else {
            throw EADLSyncException.ofState(EADLSyncException.EADLSyncOperationState.SYNCED);
        }
    } else {
        throw EADLSyncException.ofState(EADLSyncException.EADLSyncOperationState.PULL_FIRST);
    }
}
项目:JPastee    文件:JPastee.java   
/**
 * Submit a paste to the server.
 *
 * @see <a href="https://pastee.github.io/docs/#submit-a-new-paste">Pastee Docs: Submit a new paste</a>
 * @param paste the paste to submit
 *
 * @return the response of the submit request
 */
public SubmitResponse submit(Paste paste) {
    final String route = "/pastes";

    JSONObject json = new JSONObject();

    json.put("encrypted", paste.isEncrypted());
    json.putOpt("description", paste.getDescription());

    JSONArray sectionsJson = new JSONArray();
    paste.getSections().forEach(section -> {
        JSONObject sectionJson = new JSONObject();

        sectionJson.putOpt("name", section.getName());

        if(section.getSyntax() != null)
            sectionJson.putOpt("syntax", section.getSyntax().getShortName());

        sectionJson.put("contents", section.getContents());

        sectionsJson.put(sectionJson);
    });

    json.put("sections", sectionsJson);

    try {
        return new SubmitResponse(post(route, json).getBody().getObject());
    } catch(UnirestException e) {
        return new SubmitResponse(e);
    }
}
项目:eadlsync    文件:CodeRepo.java   
@Override
public String reset(String resetCommitId) throws EADLSyncException, IOException, UnirestException {
    diffManager = initDiff(resetCommitId);
    diffManager.getLocalDiff().clear();
    diffManager.applyRemoteDiff();
    writeEadsToDisk();
    return resetCommitId;
}