0

尝试将 JSON HttpRequest 发送到 SFDC Web 服务,得到以下响应:

[1]
0:  {
message: "Session expired or invalid"
errorCode: "INVALID_SESSION_ID"
}

如何使用 HttpRequest 从 LoginResult 正确传递会话 ID 或其他信息?代码示例如下:

    // Generate JSON
    MyClass object = new MyClass();
    string post_data = JsonSerializer.SerializeToString(object);   // this is what we are sending

    // this is where we will send it
    string uri = "https://url.salesforce.com/some_path/";

    // create a request
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.KeepAlive = false;
    request.Method = "POST";
    byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
    request.ContentType = "application/json";
    request.ContentLength = postBytes.Length;

    // Setup proxy and SFDC login
    LoginResult result = SfdcConnection.GetLoginResult();
    // ------------ Need to add login info here -----------------

    // now send it
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(postBytes, 0, postBytes.Length);
    requestStream.Close();

    // grab te response and print it out to the console along with the status code
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string jsonResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
4

2 回答 2

1

您需要使用 oauth 模式在 Authorization 标头中传递 sessionId,所以它是

request.Headers.Add("Authorization", "Bearer " + result.sessionId);

sessionId 可以使用很长一段时间,因此只需调用一次 login,而不是在每次 REST api 调用之前。

这在REST API 文档中有更详细的介绍。

于 2013-06-12T19:43:44.630 回答
0

您需要将LoginResult(很可能包含会话 ID)附加到您的请求中,否则,Web 服务只会看到没有会话 ID(也没有 cookie)的请求,并且无法验证您是登录。

伪代码

LoginResult result = SfdcConnection.GetLoginResult();
// attach sesionId to your request, see the web services documentation for this
request.Headers.Add("sessionId", result.sessionId);
于 2013-06-12T17:51:55.043 回答