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

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

Related

How to pass header and Body value using HttpWebRequest in C#?

Im trying to POST API credentials data to API through HttpWebRequest class in C#, like i have to pass "Content-Type:application/x-www-form-urlencoded" in Header, then have to pass "grant_type:client_credentials,client_id:ruban123,client_secret:123456" in Body to get response/token (as described in API reference).
Bellow i attached work which i did
public class DataModel
{
public string grant_type { get; set; }
public string client_id { get; set; }
public string client_secret { get; set; }
}
static void Main(string[] args)
{
try
{
DataModel dm = new DataModel();
dm.grant_type = "client_credentials";
dm.client_id = "ruban123";
dm.client_secret = "123456";
var credentials = dm.grant_type + dm.client_id + dm.client_secret;
#region Http Post
string messageUri = "https://sampleurl.apivision.com:8493/abc/oauth/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(messageUri);
request.Headers.Add("Authorization", "Basic " + credentials);
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonModel = Newtonsoft.Json.JsonConvert.SerializeObject(dm);
streamWriter.Write(jsonModel);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string jsonString = null;
using (StreamReader reader = new StreamReader(responseStream))
{
jsonString = reader.ReadToEnd();
Console.WriteLine();
reader.Close();
}
#endregion Http Post
}
catch (Exception ex)
{
}
}[API REFERENCE][1]
Here is correct HttpWebRequest using:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
request.Method = "POST";
string postData = "grant_type=client_credentials&client_id=ruban123&client_secret=123456";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
HttpWebRequest approach is not relevant. Look at this question Setting Authorization Header of HttpClient
It looks like you missed setting of ContentLength property of HttpWebRequest. It should be equal number of bytes to send.
Se this link for more information:
https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.contentlength?view=netframework-4.8

How do I access the results of a JSON object in C#

How can I loop through the JSON results from this C# Rest API call:
string url = string.Format("https://example.com/api/mytext");
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
req.Method = "GET";
req.UserAgent = "mykey";
req.Accept = "text/json";
using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
{
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
// how do I access the JSON here and loop through it?
}
}
There is no "data" in the resp object:
Visual Studio doesn't seem to show any results in "resp" - but I know they are there, as I've seen results in postman.
Thanks, Mark
Use GetResponseStream() with a StreamReader
string url = string.Format("https://example.com/api/mytext");
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
req.Method = "GET";
req.UserAgent = "mykey";
req.Accept = "text/json";
using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
{
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
string contents;
// how do I access the JSON here and loop through it?
using(var responseStream = resp.GetResponseStream())
using(var responseStreamReader = new StreamReader(responseStream))
{
contents = responseStreamReader.ReadToEnd();
}
var deserializedContent = JsonConvert.DeserializeObject<T>(contents);
}
}
See more on GetResponseStream
See more on StreamReader
See more on JsonConvert
Dependencies: Newtonsoft.Json
Use HttpWebResponse.GetResponseStream method to get the result as a Stream. Then you can use Newtonsoft JSON.NET to parse the result.
using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
{
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
using (var stream = resp.GetResponseStream())
{
// Process data with JSON.NET library here
}
}
}
dynamic dynJson = JsonConvert.DeserializeObject(response);

How to call this Delete web api method in C#?

I have the following Delete WebAPI implemented, which is working fine and tested through swagger:
//Delete IVR Paycode Profiles
[System.Web.Http.HttpDelete, System.Web.Http.Route("PayCodeProfile")]
public System.Threading.Tasks.Task<ConfirmResponse> DeleteIVRPaycodeProfile(string profileIds)
{
string orgoid = HttpContext.Current.Request.Headers["ORGOID"];
SetContext(orgoid);
return _implementation.DeleteIVRPaycodeProfileAsync(orgoid, profileIds);
}
And I am calling from client like below:
var endpointURL = new Uri("http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile/1,2,3");
var request = WebRequest.Create(endpointURL) as HttpWebRequest;
if (request != null)
{
request.Headers.Add("ORGOID", "G344G4GEJXDJJ9M5");
// sending comma separated string of ids like 1,2,
// not sure if the ContentType is correct
request.ContentType = "text/html";
request.Method = "DELETE";
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
var resp = JsonConvert.DeserializeObject<ConfirmResponse>(result);
}
}
}
But I am getting 404:Not Found error, I believe that somewhere I am making a mistake for ContentType.
the problem is your url. at first you need to send the request to this address: "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile". then depend on your content type(by default it is json) create your request. if your content type is json try this:
private static T Call<T>(string url, string body, int timeOut = 60)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeOut * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "DELETE";
request.ContentType = #"application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
reader.BaseStream.ReadTimeout = timeOut * 1000;
responseString = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(responseString);
}
then call it like this:
var url = "http://localhost/ADP.TLM.IVR/TLM/v1/IVR/PayCodeProfile";
var body = JsonConvert.SerializeObject(new { profileIds = "1,2,3" });
var output = Call<dynamic>(url, body);

Request uri too long with webservice

I want to do a create via a webservice which needs a uri like this:
http://<url>/webservice.php?operation=<operation>&elementType=<elementType>&element=<element>&
my problem is, element is all information of an email with html body, which is about 6000 characters.
I want to call the url like this:
var request = WebRequest.Create(urlToUse.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = urlToUse.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(urlToUse);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
but it breaks at
var response = request.GetResponse();
and says the uri is too long.
I can't change the server's max length of the url and the webservice needs the parameters in the url.
I haven't found a suitable solution for me yet so any help is appreciated.Update:
For anyone facing the same issue, the solution that worked for me was to put my query into an byte-Array like
var encoding = new UTF8Encoding();
byte[] bytes = enconding.GetBytes((queryString));
and writing that into the webrequest instead of my queryString
var stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
You can put data in the body of the request with something a little like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://<url>/webservice.php");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonContent = JsonConvert.SerializeObject(new YourObject
{
// Pseudo code... Replace <...> with your values etc
Operation = <YourOperation>,
ElementType = <YourElementType>,
Element = <YourElement>,
// etc...
});
HttpResponseMessage response;
using (HttpContent httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
response = await client.PostAsync("youroperation/", httpContent);
}
// Do something with response if you want
}
This is JSON based but could be anything you want to pass... This is a simple example that will hopefully give you an idea of how you can proceed.
You need to split the urlToUse at the question mark:
Something like this (not tested)
string[] parts = urlToUse.ToString().Split(new char[]{'?'}, 2);
string url = parts[0];
string data = parts[1];
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var requestStream = request.GetRequestStream();
var requestStreamWriter = new StreamWriter(requestStream);
requestStreamWriter.Write(data);
requestStreamWriter.Close();
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream == null) return null;
var responseStreamReader = new StreamReader(responseStream);
var responseFromServer = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
responseStream.Close();
response.Close();
Good luck with your quest.

Google Api get token request returns invalid_request

I'm trying to get Google APi's access_token using c# and always getting error message invalid_request. There is my code:
var Params = new Dictionary<string, string>();
Params["client_id"] = GoogleApplicationAPI.CLIENT_ID;
Params["client_secret"] = GoogleApplicationAPI.CLIENT_SECRET;
Params["code"] = "4/08Z_Us0a_blkMlXihlixR1579TYu.smV5ucbI8U4VOl05ti8ZT3ZD4CgMcgI";
Params["redirect_uri"] = GoogleApplicationAPI.RETURN_URL;
Params["grant_type"] = "authorization_code";
var RequestData = "";
foreach (var Item in Params)
{
RequestData += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value) + "&";
}
string Url = "https://accounts.google.com/o/oauth2/token";
var request = (HttpWebRequest) WebRequest.Create(Url);
request.Method = HttpMethod.Post.ToString();
request.ContentType = "application/x-www-form-urlencoded";
var SendData = Encoding.UTF8.GetBytes(RequestData);
try
{
request.ContentLength = SendData.Length;
Stream OutputStream = request.GetRequestStream();
OutputStream.Write(SendData, 0, SendData.Length);
} catch {}
try
{
using (var response = (HttpWebResponse) request.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
string JSON = sr.ReadToEnd();
}
} catch {}
I use https://developers.google.com/accounts/docs/OAuth2WebServer#offline
Try removing the call to HttpUtility.UrlEncode on each item in the request data. You shouldn't need to do this as the data is not going into the url it's being POSTed. This is no doubt diluting the information being sent which is resulting in your Invalid Request response.

Categories

Resources