Post JSON to Azure website - c#

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.

Related

get Sharepoint List View data in C# without Service Reference

I encountered som issue when using Sharepoint LIst Source on an SSIS package (too many redirection...)
My goal is to retrieve (whatever the type of result (xml, rows...) the content of a sharepoint list based on a specific view.
I only have a http://xxxxxx/_vti_bin/Lists.asmx url access.
I currently try this kind of code:
string serviceURL = "https://xxxxx/_vti_bin/Lists.asmx";
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(serviceURL);
wr.UseDefaultCredentials = true;
wr.PreAuthenticate = true;
wr.Credentials = CredentialCache.DefaultCredentials;
wr.CookieContainer = new CookieContainer();
wr.AllowAutoRedirect = false;
// wr.MaximumAutomaticRedirections = 500;
HttpWebResponse ws = (HttpWebResponse)wr.GetResponse();
Stream str = ws.GetResponseStream();
// StreamReader readStream = new StreamReader(str, Encoding.UTF8);
string xmlData;
using (StreamReader sr = new StreamReader(str, Encoding.UTF8))
{
xmlData = sr.ReadToEnd();
sr.Close();
}
At this point it seems I have no longer error (too many redirection...) but now I'm block to get columns name and value, or xml value containing all data.
Using Web Service connected to the lists.asmx failed too, so I can't use this kind of solution.
Any ideas ?
thanks in advance.
regards,

Trouble making POST request from c# [.NET]

We have a created an API for the application which takes the image via POST request process it and sends the result in JSON format.
We tried calling API from different sources like python, postman app, c#. We can successfully call end point using python and postman app but with c# getting error
c# code [Not working]
byte[] img_data = System.IO.File.ReadAllBytes(#"file_path");
string url_ep = "http://ip:port/get";
Dictionary<string, byte[]> fl_image = new Dictionary<string, byte[]>();
fl_image.Add("image", img_data);
string data = JsonConvert.SerializeObject(fl_image);
var dataToSend = Encoding.UTF8.GetBytes(data);
var request = HttpWebRequest.Create(url_ep);
request.ContentType = "application/json";
request.ContentLength = dataToSend.Length;
request.Method = "POST";
request.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
var response = request.GetResponse();
System.IO.Stream dataStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
python code [working]
import requests
url = 'http://ip:port/get'
fl_image = {'image': open('file_path', 'rb')}
res = requests.post(url, files=fl_image)
print(res.json())
API Endpoint
from flask import Flask, request
import numpy as np
import cv2 as cv
#app.route('/get', methods = ['POST'])
def get_image():
if request.method == 'POST':
file = request.files['image']
# Read file
f = file.read()
# convert string of image data to uint8
f1 = np.fromstring(f, np.uint8)
# decode image
f2 = cv.imdecode(f1,cv.IMREAD_COLOR)
There are several issues with the way you are posting data from C#. The most relevant one is that you are trying to post a file as a JSON object, with file contents as string.
This cannot work: your python server is clearly expecting multipart/form-data as content-type.
I also strongly recommend you to use HttpClient and not the old HttpWebRequest class to send HTTP Requests.
var filePath = #"file_path";
var url = "http://ip:port/get";
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
using (var fileStream = File.OpenRead(filePath))
{
var imageContent = new StreamContent(fileStream);
// NOTE: the line below is not required, but useful when you know the media type
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(imageContent, "image", Path.GetFileName(filePath));
var response = await client.PostAsync(url, content);
var stringResponse = await response.Content.ReadAsStringAsync();
// do what you need with the response
}
Other minor issues:
Do not read the entire file in memory (using File.ReadAllBytes), but open a stream for reading instead.
Use async/await when possible, do not block on async code (do not use .Result, .Wait() or .GetAwaiter().GetResult() on Task or Task<T>)
Always call Dispose() on IDisposable objects when you have finished using them (wrapping them inside a using block)
You need to dispose the connections
reader.Close();
dataStream.Close();
response.Close();
Hope this helps
Or try using HttpClient for .net within the using block

Receiving Json in HttpPost - ASP.net

I've set up a page to do an HTTP Post with a Json serialized generic list, to a different page in ASP.net. When it goes to the new page though, I can't seem to find the body of the HTTP Post.
This is the method for the post:
public static void SendHttpPost(string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:57102/Post.aspx");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
Although this is the first time I've done this, I presumed you would be able to access the Json using Request.Form or similar, but Request.Form is empty. I've had a good look at the VS degugger and can't see it anywhere in the Request object, but the content length is 68000 bytes, so I'm sure it's in there somewhere!
Can anyone point me in the right direction please? Many thanks
You can retrieve the Request Body using Request.InputStream as shown here : gist.github.com/leggetter/769688 !

Json.NET and PHP communication

I'm trying to get some communication happening between a C# .NET app and some PHP server side through JSON with Json.NET. I'm POSTing the Json string, but I can't access (or it hasn't sent correctly) the string on the server side. My $_POST variable appears empty, and I don't know what key to use to access the Json string. Can anyone suggest anything?
My C# code:
TestClass ts = new TestClass("Some Data", 3, 4.5);
string json = JsonConvert.SerializeObject(ts);
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("http://localhost/testJson.php");
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = json.Length;
StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write(json);
sw.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string responseJson = sr.ReadToEnd();
sr.Close();
TestClass returnedTS =
JsonConvert.DeserializeObject<TestClass>(responseJson);
My PHP Code:
<?php
require("TestClass.php");
$json = json_decode($_POST);
$ts = new TestClass();
$ts->someString = $json['someString'];
$ts->someDouble = $json['someDouble'];
$ts->someInt = $json['someInt'];
$return_json = json_encode($ts);
echo $return_json;
?>
My output:
<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in
<b>C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\testJson.p
hp</b> on line <b>4</b><br />
{"someString":null,"someInt":null,"someDouble":null}
You have to use application/json instead of application/x-www-form-urlencoded.
Maybe that helps!

Best way to call a JSON WebService from a .NET Console

I am hosting a web service in ASP.Net MVC3 which returns a Json string. What is the best way to call the webservice from a c# console application, and parse the return into a .NET object?
Should I reference MVC3 in my console app?
Json.Net has some nice methods for serializing and deserializing .NET objects, but I don't see that it has ways for POSTing and GETing values from a webservice.
Or should I just create my own helper method for POSTing and GETing to the web service? How would I serialize my .net object to key value pairs?
I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:
// Returns JSON string
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
I then use JSON.Net to dynamically parse the string.
Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/
POST looks like this:
// POST a JSON string
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try {
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
length = response.ContentLength;
}
}
catch (WebException ex) {
// Log exception and throw as for GET example above
}
}
I use code like this in automated tests of our web service.
WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:
using (var client = new WebClient())
{
var json = client.DownloadString("http://example.com/json");
var serializer = new JavaScriptSerializer();
SomeModel model = serializer.Deserialize<SomeModel>(json);
// TODO: do something with the model
}
There are also some REST client frameworks you may checkout such as RestSharp.
Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .
using (var client = new System.Net.Http.HttpClient())
{
return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}

Categories

Resources