简体   繁体   中英

Post JSON to Azure website

I have a string that uses JsonTextWriter to create a JSON formatted-string. How do I interact with it if I want to store it in an Azure website? I was thinking of using an httpWebRequest like

 string webAddr = "http://{url to website}/test.json";
 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
 httpWebRequest.ContentType = "application/json; charset=utf-8";
 httpWebRequest.Method = "POST"; 

 StringWriter strwriter = new StringWriter();
 JsonTextWriter writer = new JsonTextWriter(strwriter);
 writer.WriteStartObject();
 writer.WritePropertyName("id");
 writer.WriteValue(v.id);
 writer.WriteEndObject();

 using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = strwriter.ToString();

        streamWriter.Write(json);
    }

But I can't seem to figure out how to actually post the JSON to a file. Am I missing anything?

I think that it would be fine to store on the local storage of the VM/website to avoid a CORS issue, unless there is something that Blob storage would benefit over local storage.

You're part way there, next you need to actually dispatch the request:

HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

And you can read through the returned body (if required):

using (httpWebResponse)
{
    StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream());

    string response_body = reader.ReadToEnd();
}

Assuming you just wanted to dump the body to the file system (for arguments sake):

using (httpWebResponse)
{
    ...

    using (var file = new FileStream("some\path\to\file.json",FileMode.Create,FileAccess.Write,FileShare.None))
    {
        StreamWriter writer = new StreamWriter(file,Encoding.UTF8);

        writer.Write(response_body);
        writer.Flush();
    }
}

However this won't work for non VM websites, for that you'd probably have to shun the file off to blob storage.

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