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.
Related
So, I know how to get form data out by using Request.Form["abc"] however how would I go by getting the body out?
I've used this snippet in the below link:
https://gist.github.com/leggetter/769688
But, I'm not sure what to pass in as the Response.
In PHP to do this: file_get_contents('php://input'); and it's as simple as that.
Notes: The content type of the POST is application/json and the body contains the json string.
Thanks in advance.
If I understood your question correctly, here's what you could do when posting to a resource for which you expect a JSON response:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://foo.com/bar/");
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.Accept = "application/json";
HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
//store json in a variable for later use
string json = readStream.ReadToEnd();
//make sure to close
response.Close();
readStream.Close();
Of course, this approach is synchronous; but, depending on your requirements, this might be just fine.
Since your question didn't specify whether you need to know how to parse the JSON itself, so I've left out an example of JSON parsing.
You'll need code similar to this to read the raw request body into a string variable.
using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))
{
string text = reader.ReadToEnd();
}
I'm trying to use a web service to return an array to my GUI, but I don't know how to actually pull the array from the WebResponse.
This is a method in the GUI to make the call to the web service:
public static ArrayList getList()
{
String[] list;
WebRequest request = WebRequest.Create("localhost:8080/test");
WebResponse response = request.GetResponse();
list = ??? //<--What do I put here to actually access the returned array?
return response;
}
The answer to this would depend a lot on the format of the response. Is it JSON? XML?
If we assume that it is a JSON response representing a list of strings, you could do something like this:
using (var response = request.GetResponse() as HttpWebResponse)
{
Stream responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
// get the response as text
string responseText = reader.ReadToEnd();
// convert from text
List<string> results = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(responseText);
// do something with it
}
}
(this does require JSON.net)
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
¤cyCode=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";
public void HttpsRequest(string address)
{
string data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
byte[] resp = new byte[(int)response.ContentLength];
Stream receiveStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII))
{
data = reader.ReadToEnd();
}
}
I get an Arithmetic operation resulted in an overflow when I am trying to read a page over https. Errors occur because the response gives me ContentLenght = -1.
Using fiddler I can see that the page was received. Some other websites using HTTPS works fine but most of them not.
If I query https://www.google.com, I get the same error message, because not every response has a content length. Use this code to avoid the problem:
public static void HttpsRequest(string address)
{
string data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
data = reader.ReadToEnd();
}
}
}
This behavior is expected: not every response contains content length.
There is nothing in your sample that requires length to be known, so simply not reading it maybe enough.
From HttpWebResponse.ContentLength Property
The ContentLength property contains the value of the Content-Length header returned with the response. If the Content-Length header is not set in the response, ContentLength is set to the value -1.
If Content-Length header is not set it does not mean that you got a bad response.
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