This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 5 years ago.
I want to send json data in POST request using C#.
I have tried few ways but facing lot of issues . I need to request using request body as raw json from string and json data from json file.
How can i send request using these two data forms.
Ex: For authentication request body in json --> {"Username":"myusername","Password":"pass"}
For other APIs request body should retrieved from external json file.
You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:
using (var client = new HttpClient())
{
// This would be the like http://www.uber.com
client.BaseAddress = new Uri("Base Address/URL Address");
// serialize your json using newtonsoft json serializer then add it to the StringContent
var content = new StringContent(YourJson, Encoding.UTF8, "application/json")
// method address would be like api/callUber:SomePort for example
var result = await client.PostAsync("Method Address", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
You can do it with HttpWebRequest:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = "myusername",
Password = "pass"
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
This works for me.
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = "myusername",
Password = "password"
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Related
I'm consuming a Web API of an internal system in the company.
It's getting a payload in JSON format and returning a response with data in JSON format.
When sending the request with Postman, it returns the expected response (StatusCode=200 + a response text in JSON format). That means that everything is OK with the web service.
Now I have to develop an application in C# to send this HTTP request.
The problem is, that I receive as response content "OK" and not the expected JSON response gotten with Postman.
public HttpWebResponse SendRequest(string url, string checkOutFolder, string drawingNo, string login, string password)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
request.Accept = "application/json";
string payload = GeneratePayLoad(checkOutFolder, drawingNo);
string header = CreateAuthorization(login, password);
request.Headers[HttpRequestHeader.Authorization] = header;
request.ServicePoint.Expect100Continue = false;
var type = request.GetType();
var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(request);
var methodType = currentMethod.GetType();
methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(payload);
}
// Response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string responseContent = rd.ReadToEnd();
Console.WriteLine(responseContent);
}
return response;
}
Has anyone already experiences something similar.
Can you help me?
EDIT
Following your suggestions
1) Changed the method to POST -> result is still the same
2) Used Postman's code generator and RestSharp -> result is still the same
public void Request(string url, string checkOutFolder, string drawingNo, string login, string password)
{
var client = new RestClient(url);
var request = new RestRequest();
request.Method = Method.Post;
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Basic **********");
var body = GeneratePayLoad(checkOutFolder, drawingNo);
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
Console.WriteLine(response.Content);
}
Changed to HttpClient -> result still the same
using (var client = new HttpClient())
{
string uri = "******************";
string path = "destinationpath";
var endpoint = new Uri(uri);
string payload = GeneratePayLoad(path, "100-0000947591");
//FormUrlEncodedContent form = new FormUrlEncodedContent(payload);
var stringContent = new StringContent(payload);
var payload2 = new StringContent(payload, Encoding.UTF8, "application/json");
var byteArray = Encoding.ASCII.GetBytes("*******");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(client.DefaultRequestHeaders.Authorization.ToString()));
var result = client.PostAsync(endpoint, stringContent).Result.Content.ReadAsStringAsync().Result;
Console.WriteLine("test");
}
Wrote a Python code using requests Package -> delivers the same as Postman. So the problem is in the C# code.
Does anyone have an idea what is going on?
SOLVED
The issue was on the payload generation!
The request needs to be an HTTP POST and not HTTP GET because it contains JSON payload.
request.Method = "GET"; should be request.Method = "POST";
That would be one of the issue(s). I am not sure if there is something else that is wrong, but try changing the request method to POST and try again.
I have a POST Method that passes the login credentials to the API. Once the login is successful I will need to perform a GET method to retrieve some data.
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
login = "myLogin",
password = "myPassword"
});
streamWriter.Write(json);
}
//Do I implement the GET request right here? Any advice is appreciated.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Response.Write(result);
}
I Should implement the get after
var result = streamReader.ReadToEnd();
I'm trying to use C# to connect to the Nutshell API.
I'm unsure where the method name goes. Is it on the URL or as part of the JSON? I have tried both ways without success. I know my email is valid as I have tried the same method on the nutshell website
Here is my code:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.nutshell.com/v1/json/");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"method\": \"getApiForUsername\", \"user\":\"myemail#email.com.au\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
What am I doing wrong?
You want your response body to look like this:
{"jsonrpc":"2.0","method":"getUser","params":[],"id": "apeye"}
For this url:
https://app01.nutshell.com/api/v1/json
TIP: use a JSON serializer to create your JSON strings
I have a C# Console program. I just want to send JSON data to a POST RESTful service. Which approach should I follow?
#Path("/SetInfo")
public class SetInfo {
#POST
#Produces({ MediaType.APPLICATION_JSON })
#Consumes({ MediaType.APPLICATION_JSON })
public String AuthMySQL(String json) {
System.out.println("The JAX-RS runtime automatically stored my JSON request data: " + json);
return "";
}
I solved the problem.........
C# code......for sending JSON Data to webservice (post).....
var webAddr = "http://localhost:8080/TestWebservice/rest/SetInfo";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"Name\":\"MR.X\",\"ID\":\"AH1J4\"}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.Write(result);
}
How to pass in a JSON payload for consuming a REST service.
Here is what I am trying:
var requestUrl = "http://example.org";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualifiedHeaderValue("application/json"));
var result = client.Post(requestUrl);
var content = result.Content.ReadAsString();
dynamic value = JsonValue.Parse(content);
string msg = String.Format("{0} {1}", value.SomeTest, value.AnotherTest);
return msg;
}
How do I pass something like this as a parameter to the request?:
{"SomeProp1":"abc","AnotherProp1":"123","NextProp2":"zyx"}
I got the answer from here:
POSTing JsonObject With HttpClient From Web API
httpClient.Post(
myJsonString,
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));
Here's a similar answer showing how to post raw JSON:
Json Format data from console application to service stack
const string RemoteUrl = "http://www.servicestack.net/ServiceStack.Hello/servicestack/hello";
var httpReq = (HttpWebRequest)WebRequest.Create(RemoteUrl);
httpReq.Method = "POST";
httpReq.ContentType = httpReq.Accept = "application/json";
using (var stream = httpReq.GetRequestStream())
using (var sw = new StreamWriter(stream))
{
sw.Write("{\"Name\":\"World!\"}");
}
using (var response = httpReq.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Assert.That(reader.ReadToEnd(), Is.EqualTo("{\"Result\":\"Hello, World!\"}"));
}
As a strictly HTTP GET request I don't think you can post that JSON as-is - you'd need to URL-encode it and pass it as query string arguments.
What you can do though is send that JSON the content body of a POST request via the WebRequest / WebClient.
You can modify this code sample from MSDN to send your JSON payload as a string and that should do the trick:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx