Call an API with HTTP POST method and Service credentials.
336621
private <TResponse> TResponse callServicePostApi(
            String path, Map<String, String> queryParams,
            Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callPostApi(mServiceCredentials, path, queryParams, requestBody, responseClass);
    }
1034201
def run(): # pragma: no cover
    """"""
    out_file, out_format, arguments = parse()
    user, key = arguments.pop('user', None), arguments.pop('key', None)
    if not user or not key:
        sys.stderr.write('Credentials are required to perform API calls.\n')
        sys.exit(1)

    api = API(user, key, https=arguments.pop('https'), verify_ssl=arguments.pop('verify_ssl'),
              rate_limit=arguments.pop('rate_limit'))
    response = getattr(api, arguments.pop('api_call'))(**arguments)
    output = str(getattr(response, out_format) if out_format != 'list' else response.as_list())
    out_file.write(output if output.endswith('\n') else output + '\n')
565031
private void makePostCall(URL alfrescoTomcatUrl, List<NameValuePair> postData, String operation) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            // Set up a HTTP POST request to the Alfresco Webapp we are targeting
            HttpHost targetHost = new HttpHost(
                    alfrescoTomcatUrl.getHost(), alfrescoTomcatUrl.getPort(), alfrescoTomcatUrl.getProtocol());

            // Set up authentication parameters
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                    new UsernamePasswordCredentials(refreshUsername, refreshPassword));

            // Create the HTTP Client we will use to make the call
            client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();

            // Generate BASIC scheme object and add it to the local auth cache
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);

            // Add AuthCache to the execution context
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            // Make the call to Refresh the Alfresco Webapp
            HttpPost httpPost = new HttpPost(alfrescoTomcatUrl.toURI());
            response = client.execute(httpPost);
            if (postData != null) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
                httpPost.setEntity(entity);
            }
            httpPost.setHeader("Accept-Charset", "iso-8859-1,utf-8");
            httpPost.setHeader("Accept-Language", "en-us");
            response = client.execute(httpPost);

            // If no response, no method has been passed
            if (response == null) {
                getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg());
                return;
            }

            // Check if we got a successful response or not
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                getLog().info("Successfull " + operation + " for " + refreshWebappName);
            } else {
                String reasonPhrase = response.getStatusLine().getReasonPhrase();
                getLog().warn("Failed to " + operation + " for " + refreshWebappName + ". Response status: " +
                        statusCode + ", message: " + reasonPhrase);
            }
        } catch (Exception ex) {
            getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg());
            getLog().error("Exception Msg: " + ex.getMessage());
        } finally {
            closeQuietly(response);
            closeQuietly(client);
        }
    }
1152278
private <TResponse> TResponse callServiceOwnerGetApi(
            String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callGetApi(mServiceOwnerCredentials, path, queryParams, responseClass);
    }
149059
def callm(method, param_dict, POST=False, socket_timeout=None, data=None):
    
    try:
        param_dict['api_key'] = config.ECHO_NEST_API_KEY
        param_list = []
        if not socket_timeout:
            socket_timeout = config.CALL_TIMEOUT

        for key,val in param_dict.iteritems():
            if isinstance(val, list):
                param_list.extend( [(key,subval) for subval in val] )
            elif val is not None:
                if isinstance(val, unicode):
                    val = val.encode('utf-8')
                param_list.append( (key,val) )

        params = urllib.urlencode(param_list)

        orig_timeout = socket.getdefaulttimeout()
        socket.setdefaulttimeout(socket_timeout)

        if(POST):
            if (not method == 'track/upload') or ((method == 'track/upload') and 'url' in param_dict):
                """
                this is a normal POST call
                """
                url = 'http://%s/%s/%s/%s' % (config.API_HOST, config.API_SELECTOR,
                                            config.API_VERSION, method)

                if data is None:
                    data = ''
                data = urllib.urlencode(data)
                data = "&".join([data, params])

                f = opener.open(url, data=data)
            else:
                """
                upload with a local file is special, as the body of the request is the content of the file,
                and the other parameters stay on the URL
                """
                url = '/%s/%s/%s?%s' % (config.API_SELECTOR, config.API_VERSION,
                                            method, params)

                if ':' in config.API_HOST:
                    host, port = config.API_HOST.split(':')
                else:
                    host = config.API_HOST
                    port = 80

                if config.TRACE_API_CALLS:
                    logger.info("%s/%s" % (host+':'+str(port), url,))
                conn = httplib.HTTPConnection(host, port = port)
                conn.request('POST', url, body = data, headers = dict([('Content-Type', 'application/octet-stream')]+headers))
                f = conn.getresponse()

        else:
            """
            just a normal GET call
            """
            url = 'http://%s/%s/%s/%s?%s' % (config.API_HOST, config.API_SELECTOR, config.API_VERSION,
                                            method, params)

            f = opener.open(url)

        socket.setdefaulttimeout(orig_timeout)

        # try/except
        response_dict = get_successful_response(f)
        return response_dict

    except IOError, e:
        if hasattr(e, 'reason'):
            raise EchoNestIOError(error=e.reason)
        elif hasattr(e, 'code'):
            raise EchoNestIOError(code=e.code)
        else:
            raise
1096941
def post(method, hmc, uri, uri_parms, body, logon_required,
             wait_for_completion):
        """"""
        assert wait_for_completion is True  # synchronous operation
        console_uri = '/api/console'
        try:
            console = hmc.lookup_by_uri(console_uri)
        except KeyError:
            raise InvalidResourceError(method, uri)
        check_required_fields(method, uri, body, ['user-pattern-uris'])
        new_order_uris = body['user-pattern-uris']
        objs = console.user_patterns.list()
        obj_by_uri = {}
        for obj in objs:
            obj_by_uri[obj.uri] = obj
        # Perform the reordering in the faked HMC:
        for uri in new_order_uris:
            obj = obj_by_uri[uri]
            console.user_patterns.remove(obj.oid)  # remove from old position
            console.user_patterns.add(obj.properties)
840987
protected function call()
    {
        // Check if the curl object is set
        if (!$this->isInit()) {
            // If it isn't, we do it right now
            $this->init();
        }

        $options = array();
        // Set basic authentication if enabled
        if ($this->authentication instanceof BasicAuthentication) {
            $options['auth'] = array(
                $this->authentication->getUsername(),
                $this->authentication->getPassword()
            );
        }

        // Set json
        if (($json = $this->getJson()) != null) {
            $options['json'] = $json;
            $this->setAccept('application/json');
        }

        if (($formParams = $this->getFormParams()) != null) {
            $options['body'] = $formParams;
            $this->setContentType('application/x-www-form-urlencoded');
        }

        $request = $this->getHttpClient()->createRequest(
            $this->getHttpMethod(),
            $this->getEndpoint(),
            array_merge(
                array('headers' => $this->getHeaders()),
                $options
            )
        );

        foreach ($this->getEndpointParameters() as $key => $value) {
            $request->getQuery()->set($key, $value);
        }

        if (($body = $this->getBody()) != null && (is_null($body))) {
            $request->setBody(Stream::factory($body));
        }

        $response = $this->getHttpClient()->send($request);

        $this->setHttpStatusCode($response->getStatusCode());

        $this->setData($response->json());
    }
790714
def post(method, hmc, uri, uri_parms, body, logon_required,
             wait_for_completion):
        """"""
        assert wait_for_completion is True  # synchronous operation
        user_role_oid = uri_parms[0]
        user_role_uri = '/api/user-roles/' + user_role_oid
        try:
            user_role = hmc.lookup_by_uri(user_role_uri)
        except KeyError:
            raise InvalidResourceError(method, uri)
        check_required_fields(method, uri, body,
                              ['permitted-object', 'permitted-object-type'])
        # Reject if User Role is system-defined:
        if user_role.properties['type'] == 'system-defined':
            raise BadRequestError(
                method, uri, reason=314, message="Cannot add permission to "
                "system-defined user role: {}".format(user_role_uri))
        # Apply defaults, so our internally stored copy has all fields:
        permission = copy.deepcopy(body)
        if 'include-members' not in permission:
            permission['include-members'] = False
        if 'view-only-mode' not in permission:
            permission['view-only-mode'] = True
        # Add the permission to its store (the faked User Role object):
        if user_role.properties.get('permissions', None) is None:
            user_role.properties['permissions'] = []
        user_role.properties['permissions'].append(permission)
880397
def authenticate(credentials, sock_info):
    """"""
    mechanism = credentials.mechanism
    auth_func = _AUTH_MAP.get(mechanism)
    auth_func(credentials, sock_info)
1199495
protected function call()
    {
        // Check if the curl object is set
        if (!$this->isInit()) {
            // If it isn't, we do it right now
            $this->init();
        }

        $options = array();
        // Set basic authentication if enabled
        if ($this->authentication instanceof BasicAuthentication) {
            $options['auth'] = array(
                $this->authentication->getUsername(),
                $this->authentication->getPassword()
            );
        }

        $request = $this->getHttpClient()->createRequest(
            $this->getHttpMethod(),
            $this->getEndpoint(),
            array_merge(
                $options,
                array('headers' => $this->getHeaders())
            )
        );

        foreach ($this->getEndpointParameters() as $key => $value) {
            $request->getQuery()->set($key, $value);
        }

        if (($body = $this->getBody()) !== null) {
            $request->setBody(\GuzzleHttp\Stream\Stream::factory($body));
        }

        try {
            $response = $this->getHttpClient()->send($request);
        } catch (ClientException $e) {// Check if not found
            if ($e->getResponse()->getStatusCode() === StatusCodes::HTTP_NOT_FOUND) {
                throw new HttpNotFoundException();
            }

            // Check if unauthorized
            if ($e->getResponse()->getStatusCode() === StatusCodes::HTTP_UNAUTHORIZED) {
                throw new UnauthorizedException();
            }

            throw $e;
        }

        $this->setHttpStatusCode($response->getStatusCode());

        if ($this->getAccept() == 'application/json') {
            $this->setData($response->json());
        } else {
            $this->setData($response->getBody(true));
        }
    }
541358
def call_api(http_method, path, opts = {})
      response = build_request(http_method, path, opts)
      download_file response if opts[:return_type] == 'File'
      if @config.debugging
        @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
      end

      unless response.success?
        if response.status == 0
          # Errors from libcurl will be made visible here
          fail ApiError.new(:code => 0,
                            :message => response.reason_phrase)
        else
          fail ApiError.new(:code => response.status,
                            :response_headers => response.headers,
                            :response_body => response.body),
               response.reason_phrase
        end
      end
      if opts[:return_type]
        data = deserialize(response, opts[:return_type])
      else
        data = nil
      end
      [data, response.status, response.headers]
    end
287758
def _make_request(self, method, url, post_data=None, body=None):
        
        if not self.connection:
            self._connect()
        try:
            self.connection.close()
        except:
            pass
        self.connection.connect()
        headers = {}
        if self.auth_header:
            headers["Authorization"] = self.auth_header
        self.connection.request(method, url, body, headers)
        resp = self.connection.getresponse()
        return resp
435776
function _execute(httpMethod, urlSuffix, options, errorMessage) {
        const opts = {
            headers: {
                'Content-Type': 'application/json',
                'ngapimockid': ngapimockid
            }
        };

        if (options !== undefined) {
            opts.json = options;
        }

        return _handleRequest(httpMethod, urlSuffix, opts, errorMessage);
    }
506358
def post(self, url, postParameters=None, urlParameters=None):
        
        if not self.access_token:
            raise IOError("No authorized client available.")
        if not self.action_token:
            raise IOError("Need to generate action token.")
        if urlParameters is None:
            urlParameters = {}
        headers = {'Authorization': 'Bearer ' + self.access_token,
                   'Content-Type': 'application/x-www-form-urlencoded'}
        postParameters.update({'T':self.action_token})
        request = requests.post(url + '?' + self.getParameters(urlParameters),
                                data=postParameters, headers=headers)
        if request.status_code != 200:
            return None
        else:
            return toUnicode(request.text)
583352
def post(self, resource, data=None, **kwargs):
        """"""
        headers = dict(kwargs.pop('headers', {}))
        headers.setdefault('Content-Type', 'application/json')
        data = json.dumps(data)
        return self.request('POST', resource, headers=headers,
                            data=data, **kwargs)
919365
def make_api_call(self, method, url, json_params=None):
        

        url = self.BRANCH_BASE_URI+url

        if self.verbose is True:
            print("Making web request: {}".format(url))

        if json_params is not None:
            encoded_params = json.dumps(json_params)
            headers = {'Content-Type': 'application/json'}
        else:
            encoded_params = None
            headers = {}

        if encoded_params is not None and self.verbose is True:
            print("Params: {}".format(encoded_params))

        request = Request(url, encoded_params.encode('utf-8'), headers)
        request.get_method = lambda: method
        response = urlopen(request).read()
        return json.loads(response.decode('utf-8'))
585658
private <TResponse> TResponse callServiceOwnerPostApi(
            String path, Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callServiceOwnerPostApi(path, (Map<String, String>)null, requestBody, responseClass);
    }