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();
Related
I need to do this from C #, it's a post that works ok from the web, but I don't know what I'm doing wrong.
I leave a picture of the F12 when I act on the web, I try to do the same in C # but I can't get it to work.
WebRequest request = WebRequest.Create("https://xxxxxxxxxxxxx");
var Token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
request.Headers.Add("accessToken", Token);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
var data = "lockId=xxxxx";
streamWriter.Write(data);
}
var response = (HttpWebResponse)request.GetResponse();
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
MessageBox.Show(result);
}
response.Close();
}
I wanted to request using httpwebrequest class. I got error closed connection altought I setted protocol tls12 in global.asax. I tought that I should set some properties in windows server cause on local this request achieved.Here code which I created.
var httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
httpWebRequest.ProtocolVersion = HttpVersion.Version10;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(request);
streamWriter.Write(json);
streamWriter.Close();
}
DealerPaymentServicePaymentResult dealerPaymentServicePaymentResult;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
dealerPaymentServicePaymentResult = new JavaScriptSerializer().Deserialize<DealerPaymentServicePaymentResult>(result);
streamReader.Close();
}
if (dealerPaymentServicePaymentResult.ResultCode.Equals("Success"))
{
string redirectUrl = dealerPaymentServicePaymentResult.Data;
_httpContext.Session["OrderPaymentInfo"] = processPaymentRequest;//new processpayment value
return Redirect(redirectUrl);
}
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();
}
I'm getting data from web service like follow
string serviceUrl = "https://www.mscholid.com/assings/handlqueryrs/myprod.ashx";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(serviceUrl);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
var rootResult = XElement.Parse(result);
now I want to put this root result into a session
Session["rootv"] = rootResult;
then I want to retrieve it.
store function should do inside a class
public class NileResult
{
public dynamic nilecruiseFinalData_Images(string selectedID)
{
string serviceUrl = "https://www.mscholid.com/assings/handlqueryrs/myprod.ashx";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(serviceUrl);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
var rootResult = XElement.Parse(result);
//in here I want to store in to a session
}
}
how can I do this.
To access the session of the request, you can use:
HttpContext.Current.Session["rootv"] = rootResult;
HttpContext.Current is the current context of the request.
The gitWebRequest.GetResponse() line is returning a 403 error from the server and I can't seem to figure out why. Any help appreciated.
var address = new Uri(verifyUrl + _apiKey);
HttpRequest request = HttpContext.Current.Request;
var gitWebRequest = WebRequest.Create(address) as HttpWebRequest;
gitWebRequest.Method = "POST";
gitWebRequest.ContentType = "application/json";
var requestReader = new StreamReader(request.InputStream);
var requestBody = requestReader.ReadToEnd();
var myRequestUri = string.Format("{0}://{1}{2}",request.Url.Scheme,request.Url.Authority.TrimEnd('/'), request.RawUrl);
var verifyRequestData = new { requestUri = myRequestUri, postBody = requestBody };
var gitRequestData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(verifyRequestData));
using (var stream = gitWebRequest.GetRequestStream())
{
stream.Write(gitRequestData, 0, gitRequestData.Length);
}
using (var response = gitWebRequest.GetResponse() as HttpWebResponse)
{
// Get the response stream
if (response != null)
{
var responseReader = new StreamReader(response.GetResponseStream());
result = responseReader.ReadToEnd();
}
}
It was using http instead of https, which is what goole requires.
Thanks for making me look at the url.