How to get json response using system.net.webrequest in c#? - c#

I need to get json data from an external domain.
I used WebRequest to get the response from a website.
Here's the code:
var request = WebRequest.Create(url);
string text;
var response = (HttpWebResponse) request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
Does anyone know why I can't get the json data?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.
For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

You need to explicitly ask for the content type.
Add this line:
request.ContentType = "application/json; charset=utf-8";At the appropriate place

Related

Is there a way to get XML content from an API in C#?

I created a Web API in C# to return XML document, actually there is a base url and I post something to it as body of a HttpWebRequest, and as a result, I will get response that is pure XML but as string.
So I need to send this response to client but the Content-Type of response is text/plain; charset=utf-8. It should be text/xml or application/xml, I've tried some xml parser like XDocument.Parse("myXml") and XElement.Parse("myXml"), but the type was 'text' and 'json'.
I also tried XmlSerializerOutputFormatter but at this moment the type gets correct but the body consists of other characters like this < should be '<' or &gt be '>':
<string><?xml version="1.0" encoding="UTF-8"?><wfs:FeatureCollection xmlns:ogc="http://www.opengis.net/ogc" ...</string>
Well this is my code on the API side:
public dynamic Get()
{
var request = (HttpWebRequest)WebRequest.Create(url);
var data = Encoding.ASCII.GetBytes(myData);
request.Method = "POST";
// request.ContentType = "application/xml; charset=UTF-8";
// request.Accept = "application/xml; charset=UTF-8";
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();
return responseString; // text type at postman app
return XDocument.Parse(responseString); // json type in Postman app
}

Unable to post to merchant API due to error saying I must provide a request body

I spent all day trying to figure out what I was doing wrong yesterday.
Coming here to try and find some help.
The follow error is triggered when I run the actual GetResponse.
I am new to APIs so I am sure I am missing something real simple.
You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.
Here is my code I am using to try and send JSON to the API. Payment object just has the form values entered in and the credentials to use the correct account on the merchants end.
var json = JsonConvert.SerializeObject(payment);
var apiUrl = new Uri($"Removed endpoint URL");
var postBytes = Encoding.UTF8.GetBytes(json);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = postBytes.Length;
httpWebRequest.AllowWriteStreamBuffering = false;
//This is where the error triggers and drops to the catch.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
I appreciate any help in advance, I may be doing this completely wrong, its a series of things I threw together trying to fix issues with the call.
Unless I missed it, you're not actually writing your payload data to the HttpWebRequest body before you're sending it.
using (Stream _reqStrm = httpWebRequest.GetRequestStream())
{
_reqStrm.Write(postBytes, 0, postBytes.Length);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
....
Unrelated but if you can, consider HttpClient
Hth..

PayPal Pay Operation - error 81002

I'm not sure why this PayPal Pay operation is giving me this error even though I seem to have covered all the required fields:
Error Code: 81002 Severity: Error Message: Unspecified Method (Method Specified is not Supported)"
string postData = JsonConvert.SerializeObject(request);
value of postData:
"actionType=PAY
&currencyCode=USD
&cancelUrl=https%3a%2f%2fexample.com%2fcancel
&returnUrl=https%3a%2f%2fexample.com%2freturn
&requestenvelope.errorLanguage=en_US
&receiverList.receiver(0).email=recipientemail%40gmail.com
&receiverList.receiver(0).amount=0.05
&VERSION=94.0
&USER=bizemail-facilitator_api1.gmail.com
&PWD=xxxxx
&SIGNATURE=xxxxxxxxx"
Here's how I do the post:
SendRequest("https://api-3t.sandbox.paypal.com/nvp", postData);
public string SendRequest(string url, string postData)
{
var uri = new Uri(url);
var request = WebRequest.Create(uri);
var encoding = new UTF8Encoding();
var requestData = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Timeout = (300*1000); //TODO: Move timeout to config
request.ContentLength = requestData.Length;
using (var stream = request.GetRequestStream()) {
stream.Write(requestData, 0, requestData.Length);
}
var response = request.GetResponse();
string result;
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII)) {
result = reader.ReadToEnd();
}
return result;
}
The method PAY doesn't exist on the NVP api. Full list of methods supported by that API is found here.
The PAY method, however, is defined in the Adaptive Payments API. Depending on your needs, you have two options:
Change the endpoint to https://svcs.paypal.com/AdaptivePayments/PAY and modify your values
Use another method, like DoDirectPayment, but I'm not sure it does what you want to.
I assume the value of postData is before you serialize it to a JSON string, instead of after as you say, since it is clearly not a JSON string.
If so, then it is already x-www-form-urlencoded, and you do not need to serialize it to a JSON string at all.
Or if you do after all, then change just this: request.ContentType = "application/json";

Can you pass form variables and a json object at the same time using HttpWebRequest?

I need to post a json string and a form variable to a url (https://www.somedomain.com/checkout.jsp).
My json will contain order information (user email, shipping address, billing address, credit card number, etc). In addition to the json string I need to pass in a form variable like "bmForm=submit_order_service."
Currently I am attempting to do this via the HttpWebRequest object in ASP.Net MVC 3 (C#).
Here is the code that handles just the json string. So, my question is, how do I modify this code to also pass in the form variable as well.
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.somedomain.com/checkout/checkout.jsp");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "*/*";
httpWebRequest.UserAgent = "SomeUserAgent";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = sb.ToString();
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
If it's not possible to do what I am asking using HttpWebRequest, maybe someone can recommend an alternative approach?
You can HTML encode your form data and append it to the URL as parameters : http://www.somedomain.com/checkout/checkout.jsp?param1=value1&param2=value2... . Basically, treat the form as if its action is set to GET (but use the POST HTTP verb, of course).
If you want to have both the Json and the form parameters inside the "Post-Data" you're going to have to urlencode your json and add it as a form parameter along with the other form parameters:
e.g.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://mysite.com/index.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "json=[yoururlencodedjson]&var2=value2&var3=value3"
req.ContentLength = postData.Length;
Essentially you will need to find out from the service provider which format they expect.

How to POST Raw Data using C# HttpWebRequest

I am trying to make a POST request in which I am supposed to send Raw POST data.
Which property should I modify to achieve this.
Is it the HttpWebRequest.ContentType property. If, so what value should I assign to it.
public static string HttpPOST(string url, string querystring)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded"; // or whatever - application/json, etc, etc
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
try
{
requestWriter.Write(querystring);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
You want to set the ContentType property to the mime type of the data. If its a file, it depends on the type of file, if it's plain text then text/plain and if it's an arbitrary binary data of your own local purposes then application/octet-stream. In the case of text-based formats you'll want to include the charset along with the content type, e.g. "text/plain; charset=UTF-8".
You'll then want to call GetRequestStream() and write the data to the stream returned.

Categories