简体   繁体   中英

Simple REST request c# - error

I am trying write simple request to REST service.Follow to documentation from REST Service provider:

  1. I should use in header Content-Type: application/json.
  2. Response return in json format
  3. For authorization proccess I have to send two headers one with APIKey and second with APISign

Controller PING in REST service to test code.

I use .net 2.0

    string sha1String = APIKey + "/rest/ping" + APISecret;
string XRestApiSign = SHA1HashStringForUTF8String(sha1String);
string data = "";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restServer);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-Rest-ApiSign", XRestApiSign);
request.Headers.Add("X-Rest-ApiKey", APIKey);

request.ContentLength = data.Length;

StreamWriter requestWriter;

Stream webStream = request.GetRequestStream();
using (requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII)) ;
{
    requestWriter.Write(data);
}

request.BeginGetResponse((x) =>
{
    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(x))
    {
        List<string> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(response.GetResponseStream().ToString());
    }
}, null);

I should get response string PONG but I get below message

Unexpected character encountered while parsing value: S. Path '', line 0, position 0

Is code OK ? Why I get this message?

This is mostly the case because the script that generates the JSON on the server side adds the byte order mark to the response.

In your case, however, you're trying to convert the stream to JSON, not the content of the stream. You need to read all text from the stream and deserialize the object from that. You need to call one of the methods on the stream that reads the content.

I modified my code with yours suggestion and it works. Now I have problem with send data :)

 Subscription user1 = new Subscription
 {
     Email = "kubaIt@test.com.pl",
     List  = "xfct2bjcdv",
 };

 List<Subscription> user = new List<Subscription>();
 user.Add(user1);

string json = JsonConvert.SerializeObject(user);
string data = json;

I added above. Other code is the same. I got error :The request was aborted: The request was canceled."

json = [{\\"email\\":\\"kubaIt@test.com.pl\\",\\"list\\":\\"xfct2bjcdv\\"}] //value from debuger

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM