带标头的Callrail API HTTP GET请求

时间:2017-03-29 22:23:12

标签: jquery ajax get

我可以将它扔进linux终端并获得结果。

curl -H "Authorization: Token token={api_token}" \
 -X GET \
 "https://api.callrail.com/v2/a/{account_id}/calls.json?company_id={companyId}"

这就是我所拥有的:

var myToken = "fakeToken1234";

$.ajax
    ({
        type: "GET",
        url: "https://api.callrail.com/v2/a/{accountId}/calls.json?company_id={companyId}",
        dataType: 'json',
        beforeSend: function (xhr) { xhr.setRequestHeader('Authorization:', + myToken ); }
    });

Per CallRail Documentation我应该将api_token传递给HTTP Authorization标头。我收到401 Unauthorized消息。

我认为我的语法已关闭,但无法将其固定下来。有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

这是我尝试使用“headers:”:

package org.springframework.social.facebook.connect;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.social.support.ClientHttpRequestFactorySelector;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class FacebookOAuth2Template extends OAuth2Template {

    private static final Logger LOGGER = LogManager.getLogger(FacebookOAuth2Template.class);

    public FacebookOAuth2Template(String clientId, String clientSecret) {
        super(clientId, clientSecret, "https://www.facebook.com/v1.0/dialog/oauth", "https://graph.facebook.com/v1.0/oauth/access_token");
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate(ClientHttpRequestFactorySelector.getRequestFactory());
        FormHttpMessageConverter messageConverter = new FormHttpMessageConverter() {
            @Override
            public boolean canRead(Class<?> clazz, MediaType mediaType) {
                // always read as x-www-url-formencoded even though Facebook sets contentType to text/plain
                return true;
            }
        };
        restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>> singletonList(messageConverter));
        return restTemplate;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        MultiValueMap<String, String> response = getRestTemplate().postForObject(accessTokenUrl, parameters, MultiValueMap.class);
        String expires = response.getFirst("expires");
        String accessToken = response.getFirst("access_token");
        if(!response.keySet().isEmpty() && (StringUtils.isEmpty(expires) || StringUtils.isEmpty(accessToken))) {
            for(String key : response.keySet()) {
                boolean valuesFound = false;
                HashMap<String, String> map;
                try {
                    //map = (HashMap<String, String>) JSONUtil.fromJSON(key, HashMap.class);
                    ObjectMapper objectMapper = new ObjectMapper();
                    map = objectMapper.readValue(key, HashMap.class);

                    if(StringUtils.isEmpty(expires)) {
                        expires = String.valueOf(map.get("expires_in"));
                        valuesFound = true;
                    }

                    if(StringUtils.isEmpty(accessToken)) {
                        accessToken = map.get("access_token");
                        valuesFound = true;
                    }

                    if(valuesFound) {
                        break;
                    }
                } catch(IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        return new AccessGrant(accessToken, null, null, expires != null ? Long.valueOf(expires) : null);
    }
}

不要忘记在您的网址中加载companyId和accountId。我假设你顺便在这个答案中使用了正确的网址。

希望它有效。到目前为止,我只使用一个API执行$ .ajax请求。所以让我听听它是否有效。它至少应该指向正确的方向。

答案 1 :(得分:0)

我的问题是我没有理解CallRail在标题中想要的语法。

这解决了它:headers: { "Authorization": 'Token token=' + myToken },

var myToken = "token1234";
var accountId = "Id1234";
var companyId = "Id1234";     

$.ajax
    ({
        type: "GET",
        url: "https://api.callrail.com/v2/a/" + accountId + "/calls/timeseries.json?company_id=" + companyId + "",
        dataType: 'json',
        headers: { "Authorization": 'Token token=' + myToken },
            success: function (result) {
                console.log(result);
            },
    });
相关问题