I'm new in c# ,and want to send json post to server with this code:
var httpWebReques = (HttpWebRequest) WebRequest.Create(#"http://myDomain/api/FileCommand/AddGig ");
httpWebReques.ContentType = "application/json";
httpWebReques.Method = "POST";
using (var streamWriter=new StreamWriter(httpWebReques.GetRequestStream()))
{
JObject obj = JObject.FromObject(new
{
PhoneNumber= phoneNumber,
TrafficGigCount="1",
PaymentAmountRial="2000",
PaymentTrackingNo="123434"
});
string json = obj.ToString(); //"{\"PhoneNumber\":\""+phoneNumber+"\"," + "\"TrafficGigCount\":\"1\","+ "\"PaymentAmountRial\":\"1000\","+ "\"PaymentTrackingNo\":\"1254\"}";
streamWriter.Write(obj);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse) httpWebReques.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
every thing is ok and now want to send server cookie with this code:
httpWebReques.CookieContainer = new CookieContainer();
httpWebReques.CookieContainer.SetCookies(new Uri("http://www.tclnet.ir/"), cookies);
for that purpose write this code:<br/>
var httpWebReques = (HttpWebRequest) WebRequest.Create(#"http://www.tclnet.ir/api/FileCommand/AddGig ");
httpWebReques.ContentType = "application/json";
httpWebReques.Method = "POST";
httpWebReques.CookieContainer = new CookieContainer();
httpWebReques.CookieContainer.SetCookies(new Uri("http://www.tclnet.ir/"), cookies);
using (var streamWriter=new StreamWriter(httpWebReques.GetRequestStream()))
...
but when receive to this line:
var httpResponse = (HttpWebResponse) httpWebReques.GetResponse();
get this error:
The remote server returned an error: (500) Internal Server Error.
How can i solve that?thanks.
my error:
Related
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
i have a web app connected with crm Dynamics 365. I want to create record in an entity using API, but the entity has lookup fields to another entities. I tried this code but it gives bad request error. How can i send the values of the lookup fields in the API?
JSON:{
"msdyn_name": "Asset",
"msdyn_account#odata.bind": "/accounts(7f7e031b-0e20-ea11-a810-000d3a2d54fd)",
"new_externalproj#odata.bind": "/msdynce_externalprojects(ee3f03c6-751f-ea11-a810-000d3a27b751)" }
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
msdyn_name = "Asset",
msdyn_account = "7f7e031b-0e20-ea11-a810-000d3a2d54fd",
new_externalproj = "ee3f03c6-751f-ea11-a810-000d3a27b751"
});
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://XXX.dynamics.com/api/data/v9.1/msdyn_customerassets");
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", String.Format("Bearer {0}", result.AccessToken));
httpWebRequest.Headers.Add("OData-MaxVersion", "4.0");
httpWebRequest.Headers.Add("OData-Version", "4.0");
httpWebRequest.ContentType = "application/json";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
I am calling an API but its giving me below error:
UriFormatException: Absolute URI is too short
Please check below code:
void updatePlayer ()
{
HttpWebRequest httpWebRequest = WebRequest.Create (requestURL) as HttpWebRequest;
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add ("x-api-key", "e1Zdd1YD92aJtpyDaCtSDTZCrDXtv2c9Cf");
string json = "{" +
"'firstName': '100'," +
"'lastName': 'DEF'" +
"}";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
streamWriter.Write (json);
}
httpWebRequest.ContentLength = json.Length;
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse ();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
var responseText = streamReader.ReadToEnd ();
//Now you have your response.
//or false depending on information in the response
Debug.Log (responseText);
}
}
in php i post a request like
$.post("/service.php?cat=c1", {
group: $this.attr('href'),
})
where group -> #$!/mycat/year,2012
now i want to do same request in c#
var httpWebRequest = (HttpWebRequest)WebRequest.Create( url);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
I tried
String url = domain + "./service.php?cat=c1&group=%22#$!/mycat/year,2012%22";
and
String url = domain + "./service.php?cat=c1&group=mycat&year=2012";
but "message" always returns empty
What is the problem here?
You can use the WebClient class, as this is easier to use.
Pass in the values as NameValueCollection object
var client = new WebClient();
var nameValueCollection = HttpUtility.ParseQueryString("cat=c1&group=mycat&year=2012");
var response = client.UploadValues(domain + "/service.php","POST",nameValueCollection);
var responseStr = Encoding.ASCII.GetString(response);
Here is my code:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "someParameters";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
string Bugzilla_logincookie= httpResponse.Headers.ToString();
Bugzilla_logincookie= Bugzilla_logincookie.Substring(plsWork .IndexOf("logincookie") + 12);
Bugzilla_logincookie= Bugzilla_logincookie.Substring(0, plsWork .IndexOf(";"));
CookieContainer cc = new CookieContainer();
cc.SetCookies(new Uri("http://localhost"), Bugzilla_logincookie);
var httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/jsonrpc.cgi");
httpWebRequest2.ContentType = "application/json";
httpWebRequest2.Method = "POST";
httpWebRequest2.Proxy.Credentials = new NetworkCredential("username", "password");
httpWebRequest2.CookieContainer = cc;
using (var streamWriter2 = new StreamWriter(httpWebRequest2.GetRequestStream()))
{
string json = "someParametersForJsonCall";
streamWriter2.Write(json);
}
var httpResponse2 = (HttpWebResponse)httpWebRequest2.GetResponse();
using (var streamReader2 = new StreamReader(httpResponse2.GetResponseStream()))
{
var responseText = streamReader2.ReadToEnd();
}
I have problem with using proxy. The thing I'm trying to do is: use a Proxy for http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/User.html to call the login method and then store cookies of response and send them with each call of the session.
I get this error:
"You must log in before using this part of Bugzilla."
What am I mistakenly using?