C# Console Application httpWebRequest - c#

Im trying to create a very simple c# console application to post some data to a web api. However whatever I do I get an error on the response like:
responseText "{\"info\":{\"status\":\"failed\",\"error\":{\"code\":1000,\"message\":\"Invalid argument from request\"}}}" string
The api http://www.detrack.com/api-documentation/ is looking for a post like
https://app.detrack.com/api/v1/deliveries/view/all.json?key=dab13cc0094620102d89f06c0e464b7de0782bb979258d3a&json={"date":"2014-08-29"}
I know using this in chrome advanced rest application extension returns a valid result. But When I try the same via this console code. I get an error!.
Here is the code I have in my console application.
using System;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://app.detrack.com/api/v1/deliveries/view/all.json?key=dab13cc0094620102d89f06c0e464b7de0782bb979258d3a&");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "json={\"date\":\"2014-08-28\"}";
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadKey();
}
}
}
}
Any help/guidance would be really appreciated
brendan

So I'm looking at this:
string json = "json={\"date\":\"2014-08-28\"}";
And according to the brief description on detrack that is not what you want. They're expecting valid json and that isn't. Here's what you should be considering valid json:
string json = "{\"date\":\"2014-08-28\"}";
Be warned I don't know about your escaping of quotes. I would serialize that differently; either a strongly typed class or an anonymous class. Anon would look like this:
string json = JsonConvert.DeserializeObject(new { date = "2014-08-28" });
Setting aside any concerns about time, timezones, utc, etc, that will serialize your structures correctly. Here's a scratchy program from linqpad:
void Main()
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { date = "2014-08-28"});
Console.WriteLine(json);
}
>>> {"date":"2014-08-28"}

You can try the (untested!) code below.
using System;
using System.Net;
using System.IO;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
var webAddr = "https://app.detrack.com/api/v1/deliveries/create.json";
var httpWebRequest = (HttpWebRequest) WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
string postData = "key=dab13cc0094620102d89f06c0e464b7de0782bb979258d3a&json={""date"":""2014-08-28""}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
httpWebRequest.ContentLength = byteArray.Length;
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(byteArray, 0, byteArray.Length);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
MessageBox.Show(result);
}
}
}
}

Related

how to add body in post request c# [duplicate]

This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 1 year ago.
i, tried putting body in request but didn't actually worked,
in body i want to put which is in json format {"ClaimNo":"123123"}
i have used this as code:
string ClaimStatus_url = "https:xyz";
WebRequest request = WebRequest.Create(ClaimStatus_url);
request.ContentType = "application/json";
request.Method = "POST";
//request.Headers = "";// i used this for puting body in it but did not work
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string result = reader.ReadToEnd();
using System.Text;
using System.Text.Json;
namespace TestPostData;
public class Data
{
public int ClaimNo { get; set; }
}
public static class Program
{
public static void Main()
{
var postData = new Data
{
ClaimNo = 123123,
};
var client = new System.Net.Http.HttpClient();
var content = new StringContent(JsonSerializer.Serialize(postData), Encoding.UTF8, "application/json");
var response = client.PostAsync("https:xyz", content).Result;
}
}
That is an example of using HttpClient class that is now recommended to use instead WebRequest.
Try this, i hope it will work.
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I would start off by using RestSharp.
dotnet add package RestSharp
Then I would create a DTOS object with the contents that you want to send in the json:
public class DtosObject
{
public string ClaimNo {get; set;}
}
Then pass that in as the object (I would call the class something relevant to the data it contains). If you only are using ClaimNo you could also use a KeyValuePair like this:
var body = new KeyValuePair<string, string>("ClaimNo", "123123");
Then you can send requests like this:
public async Task<IRestResult> PostAsync(string url, object body)
{
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.Post);
request.AddJsonBody(body);
var response = await client.ExecuteAsync(request);
return response;
}
string ClaimStatus_url = "https://qms.xyz.in/FGClaimWsAPI/api/Common/FetchClaimdetails";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(ClaimStatus_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"ClaimNo\":\""+ userProfile.ClaimNumber +"\"}";
//string json = "{\"ClaimNo\":\"CV010831\"}";
//await turnContext.SendActivityAsync(MessageFactory.Text(json, json), cancellationToken);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result1 = "" ;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
result1 = result.Substring(1, result.Length -2); // to bring response result in proper format
}
_claimstaus = GenrateJSON_Claim(result1);
This upper code worked

Cannot submit form data via POST API call

I'm trying to make a POST API call to update a product on Prisync with multipart/formdata text field.
The call responses success on POSTMAN:
but it returns 400 Bad request error in .NET code:
Can you please let me know what's wrong here?
Here is my code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
namespace PrisyncPost
{
class Program
{
static string apikey = "luan.t44#gmail.com";
static string apitoken = "3a3206b37763722c0fc6431b713d9239";
static void Main(string[] args)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://prisync.com/api/v2/edit/product/id/10117217");
httpWebRequest.Method = "POST";
httpWebRequest.Headers["apikey"] = apikey;
httpWebRequest.Headers["apitoken"] = apitoken;
httpWebRequest.ContentType = "multipart/form-data; boundary=&";
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent("test test test"), "name");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
foreach (var item in form)
streamWriter.Write(item);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
}

c# Json Post throws 404 bad request error

I am new to JSON and C# and trying for a POST request and reading the response.
I am writing the Content Type correctly, url I am trying to send to the server is also correct. Probably my code is just incorrect and I will appreciate for any helps on this.
Below is my code but I keep getting 400 bad request.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
public class Server
{
public void ServerStart()
{
try{
string webAddr="https://localhost:61000/users/login";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"userName\" : \"laborel\", \"userPassword\" : \"dGVzdG5ldFBDMSEu\" }";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
byte[] responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
}catch(WebException ex){
Console.WriteLine(ex.Message);
System.Windows.Forms.MessageBox.Show(string.Format ("Exception Occurred: {0}",ex.Message));
}
}
}
One thing byte[] responseText = streamReader.ReadToEnd(); is not right, where I am not sure what should bet the responseText
Could some one point me out on how can we create a function which accepts the webaddress and the json string as input and returns the response text
Following would work string responseText = streamReader.ReadToEnd();

How to Request Specific Object From JSON URL with C# WebClient

Following code returns entire JSON objects but I need to Filter to some specific Object, for example I need to get only the "layers" or tiltle can you please let me know how to do this is C#?
Do I have to create an HttpWebRequestobject for this? if so where should I pass the requested data?
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
Console.WriteLine(json);
}
I already tried this but it is also returning everything
class Program
{
private const string URL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson";
private const string DATA = #"{{""layers"":""Layers""}}";
static void Main(string[] args)
{
CreateObject();
}
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = DATA.Length;
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(DATA);
}
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
Console.WriteLine(response);
Console.ReadLine();
}
}
}
}
catch (Exception e)
{
Console.WriteLine("-----------------");
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
If you need the info related to the layers array object then you can use following code
using (var wc = new WebClient())
{
string json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
dynamic data = Json.Decode(json);
Console.WriteLine(data.layers[0].id);
Console.WriteLine(data.layers[0].name);
Console.WriteLine(data.documentInfo.Title);
}

Call to OData service from C#

I use the code below to call an OData service (which is the working service from Odata.org) from C# and I don't get any result.The error is in the response.GetResponseStream().
Here is the error :
Length = 'stream.Length' threw an exception of type 'System.NotSupportedException'
I want to call to the service and parse the data from it, what is the simpliest way to do that?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;
namespace ConsoleApplication1
{
public class Class1
{
static void Main(string[] args)
{
Class1.CreateObject();
}
private const string URL = "http://services.odata.org/OData/OData.svc/Products?$format=atom";
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/xml";
request.Accept = "application/xml";
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
}
}
}
}
}
I ran your code on my machine, and it executed fine, I was able to traverse all XML elements retrieved by the XmlTextReader.
var request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/xml";
request.Accept = "application/xml";
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
var reader = new XmlTextReader(stream);
while (reader.Read())
{
Console.WriteLine(reader.Value);
}
}
}
But as #qujck suggested, take a look at HttpClient. It's much easier to use.
If you're running .NET 4.5 then take a look at HttpClient (MSDN)
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(endpoint);
Stream stream = await response
.Content.ReadAsStreamAsync().ConfigureAwait(false);
response.EnsureSuccessStatusCode();
See here and here for complete examples

Categories

Resources