I am sending an HTTP post request using HTTPWebRequest to an URL. I am sending the post data using multipart/form-data content type along with the content length of the body. However, on the server side, I am unable to retrieve the body. I can only see the headers sent. The content length of the body I sent also matches.
Why am I not able to retrieve the body.
The request method looks like this:
public void Reset(string originalFileData, string uploadLocation)
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(Server), portNo);
client.Connect(serverEndPoint);
string responseContent;
string serverUrl = "http://" + Server + ":" + portNo + "/abc.aspx" + "?uplvar=" + uploadLocation;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUrl);
request.ContentType = "multipart/form-data";
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string postData = originalFileData;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
}
Edit: I forgot to mention, I am able to retrieve the body on the first time I send the request, but on any subsequent requests I send, I am not able to retrieve it. I am creating a new connection each time I send a request. So, something might be preventing the request body from being retrieved. I am not sure why.
Try replacing
request.ContentType = "multipart/form-data";
with
request.ContentType = "application/x-www-form-urlencoded";
or check this SO answer for code which works with multipart/formdata.
Related
The request gives the following error:
The remote server returned an error: (400) Bad Request.
I cann't find a solution on internet. Does anyone knows how to solve this?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"https://maps.googleapis.com/maps/api/geocode/json");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var parameters = string.Format("language={0}&latlng={1}&client={2}&signature={3}", "nl", "51.123456,5.612345", "gme-aa", "******_******=");
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
/*
* Read HttpWeb Response
*/
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string Response = reader.ReadToEnd();
response.Close();
EDIT:
I'm working inside Lowcode platform Outsystems. Outsystems creates the url inside WebRequest.Create() without the paramaters. So, I have access to webRequest object and need to pass the parameters.
You have to use HTTP "GET" Method.
In a GET request, you pass parameters as part of the query string.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://maps.googleapis.com/maps/api/geocode/json?language=fr&latlng=51.123456,5.612345&key={apiKey}");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
According the documentation, the API is expecting a POST method and receiving the parameters in the URL and not the body.
If you are using the OutSystems platform you can use the Consume REST API functionality to easily call the web service without using code. Configure your API like this (you can copy the example JSON from the documentation page above):
I'm creating a application, and in one of it's functionalities I need to send json code over web request.
I use Get, Post, Put and Delete. And I already can create the connection and send and receive data.
But, for every request I should receive json code. Which I believe I am receiving, but I can't read it...
I'l put some code sample so you can see if there is something I can make to read that json code
First the Get request:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (this.getURL ());
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
var response = (HttpWebResponse)webRequest.GetResponse ();
var responseString = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
webRequest.Abort();
return JArray.Parse (responseString);
This is the only case where I can read the json answer.
Next Post request:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (this.getURL ());
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
var data = Encoding.UTF8.GetBytes(request);
webRequest.ContentLength = data.Length;
Stream stream = webRequest.GetRequestStream ();
stream.Write (data, 0, data.Length);
stream.Close ();
var response = (HttpWebResponse)webRequest.GetResponse();
webRequest.Abort();
return (int)response.StatusCode;
In this example I solved my problem using the response code.. which can only be 200, because every other code Is assumed as some exception.
For put and delete will be the same as post.
As I said I need to receive the json code. and not only the response code.
I would be really grateful if you could help-me in this problem.
Thanks to Orel who tried do help.
I got mt problem solved, I will post a sample code for everyone who might need this kind of solution.
My problem actually was very simple.
When I used "POST" in a web request I would create a stream to actually post my data. And then I would try to get my answer from that same stream, when actually I was getting the information I needed In the webRequest var.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (this.getURL ());
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
var data = Encoding.UTF8.GetBytes(request);
webRequest.ContentLength = data.Length;
Stream stream = webRequest.GetRequestStream ();
stream.Write (data, 0, data.Length);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var responseString = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
stream.Close ();webRequest.Abort();
return JObject.Parse(responseString);
I've been fiddling quite a bit with my uploading to vimeo.
I've made a ticket request.
I've uploaded the file.
I've checked the file if its uploaded.
I need to run the method DELETE with the complete_uri response i should get from my ticket.
However, im not receiving any complete_URI from the ticket response.
Here is my code:
public static dynamic GenerateTicket()
{
const string apiUrl = "https://api.vimeo.com/me/videos?type=streaming";
var req = (HttpWebRequest)WebRequest.Create(apiUrl);
req.Accept = "application/vnd.vimeo.*+json;version=3.0";
req.Headers.Add(HttpRequestHeader.Authorization, "bearer " + AccessToken);
req.Method = "POST";
var res = (HttpWebResponse)req.GetResponse();
var dataStream = res.GetResponseStream();
var reader = new StreamReader(dataStream);
var result = Json.Decode(reader.ReadToEnd());
return result;
}
This response gives me:
form
ticket_id
upload_link
upload_link_secure
uri
user
In order to finish my upload i need to run step 4 in this guide: https://developer.vimeo.com/api/upload
Sending parameter type=streaming as body:
ASCIIEncoding encoding = new ASCIIEncoding();
string stringData = "type=streaming"; //place body here
byte[] data = encoding.GetBytes(stringData);
req.Method = "PUT";
req.ContentLength = data.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
At the moment, type=streaming must be sent in the body of the request, not as a url parameter.
This will probably change to allow either option.
the important point is :
"The first thing you need to do is request upload access for your application. You can do so from your My Apps page."
If you get all values without complete_uri, it means: you dont have an upload access token. So go to your apps and make an upload request
Iam developing a cross platform android app in Xamarin. I want to send a request to register my device. Iam sending my DeviceId, DeviceName and EncodedAccountName i.e my email id.
But I dont get any response. I have tested the request on Postman and get a proper response.
Here is my code:
StringBuilder registerContent = new StringBuilder();
registerContent.Append("DeviceId=").Append(deviceId).Append("&");
registerContent.Append("Name=").Append(deviceName).Append("&");
registerContent.Append("EncodedAccountNameā€¸=").Append(username);
WebRequest request = WebRequest.Create(EndPoints.RegisterDeviceEndPoint);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = registerContent.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType= "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();// Dont get any response here
// Display the status.
System.Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
System.Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return response.ToString();
Any ideas on what might me going wrong?
Thanks
This is how I notify my Web API and wait for a string response:
string myParameters = "?firstParam=" + someParam1 + "&secondParam=" + someParam2;
string url = someHTTPAddress + myParameters;
stringResponseFromWebAPI = (new WebClient()).DownloadString(url);
i am facing a problem where i try to communicate with a Ruby API from a C# application.
I need to POST some JSON data, with the parameter name "data" but the API return me: '!! Unexpected error while processing request: invalid %-encoding'.
I tried with Content-Type set to 'application/json' and 'application/x-www-form-urlencoded; charset=utf-8'.
My POST data look like this 'data=some_json_string'.
I figure i should escape the json string, so if it is my problem, how to do it with .NET without using a 3rd party library?
Code:
byte[] data = System.Text.ASCIIEncoding.UTF8.GetBytes(sdata);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.Absolute));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
request.ContentLength = data.Length;
Stream reqStream = request.GetRequestStream();
// Send the data.
reqStream.Write(data, 0, data.Length);
reqStream.Close();
Thanks in advance!
Presuming the string sdata coming in is already in JSON format you could do:
using (WebClient wc = new WebClient())
{
string uri = "http://www.somewhere.com/somemethod";
string parameters = "data=" + Uri.EscapeDataString(sdata);
wc.Headers["Content-type"] = "application/x-www-form-urlencoded";
string result = wc.UploadString(uri, parameters);
}
Depending on the consuming service it may need the Content-type set to application/json?