I am currently working on implementing a class for accessing rest webservices with my C# program. I managed to do that for PUT, Post and GET, but I have problems with the Patch. The following error occurs everytime:
There is an exception error “System.Net.WebException” in System.ddll
Additional information: remote server reported: (400) Unvalid request
I have researched and tried out various things – to no avail. I would appreciate any help!
Many thanks in advance
public string WebserviceSenden()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create( GrundURL + ErweiterungsURL);
// Set the Method property of the request to POST.
request.Method = Methode;
// Create POST data and convert it to a byte array.
string postData = DateSenden;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// 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();
// Display the status.
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.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
public string WebserviceEmpfangen()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create(
GrundURL + ErweiterungsURL);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream 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.
Console.WriteLine(responseFromServer);
// Clean up the streams and the response.
reader.Close();
response.Close();
return responseFromServer;
}
}
private void button1_Click(object sender, EventArgs e)
{
String Jason = "";
RestClient AbfrageStarten = new RestClient();
AbfrageStarten.GrundURL = "URL";
AbfrageStarten.ErweiterungsURL = "540697";
Jason = AbfrageStarten.WebserviceEmpfangen();
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var list = JsonConvert.DeserializeObject<List<Lagereinheit>>(Jason, settings);
KorrekturLagereinheit = list[0];
KorrekturLagereinheit.stueckzahl = 5858;
string Test;
Test = JsonConvert.SerializeObject(KorrekturLagereinheit, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
RestClient AntwortSenden = new RestClient();
AntwortSenden.GrundURL = "URL";
AntwortSenden.ErweiterungsURL = "540697";
AntwortSenden.Methode = "Patch";
AntwortSenden.DateSenden = Test;
AntwortSenden.WebserviceSenden();
}
Error message
Many thanks in advance
Related
i am trying to send xml data from file to sensor what should get XML and make a values from that. I have this code, but i don't know if it is actually working.
I do have response from server but does it actually get those data from xml file? I am still newbie so i still don't know.
Thank you for any help..
class Program
{
static void Main(string[] args)
{
WebRequest request = WebRequest.Create("http://192.168.254.20:5050/token");
request.Method = "POST";
string postData = #"C:\Users\lvrabel\Desktop\Crajsons\finals\Output.xml";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/xml";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
Console.WriteLine(postData);
Console.ReadKey();
reader.Close();
dataStream.Close();
response.Close();
}
}
You need to read your xml file then you can convert it to bytes and then you can post it to server.
byte[] xmlData= File.ReadAllBytes(#"C:\Users\lvrabel\Desktop\Crajsons\finals\Output.xml");
This is an other approach:
var xmlFile = #"C:\Users\lvrabel\Desktop\Crajsons\finals\Output.xml";
var client = new HttpClient { BaseAddress = new Uri("http://192.168.254.20:5050/")};
using(var content = new StringContent(File.ReadAllText(xmlFile), Encoding.UTF8, "text/xml"))
{
var result = await client.PostAsync("token", content);
var respnseText = await result.Content.ReadAsStringAsync();
}
(Note: if you are accessing the same service endpoint with the same settings multiple times you can reuse the HttpClient instance to call the different service methods even across threads. This is why I have not wrapped it into a using clause)
If you have difficulties communicating with the service you might have other problems. If you don't get an exception then you can inspect the properties of the result to see if the service endpoint returned success (OK=200) or some other result code. You might find details about it. You could also simply reproduce this code in html+javascript, there you can more easily inspect the traffic in the browser. Of course, you could use some network sniffer, but that can be far more complicated.
[Update]
If you really only need to pass the file name as GET parameter, then use something like this:
var xmlFile = #"C:\Users\lvrabel\Desktop\Crajsons\finals\Output.xml";
var uri = new Uri($"http://192.168.254.20:5050/token?content={xmlFile}", UriKind.Absolute);
using (var client = new HttpClient())
{
var result = await client.GetAsync(uri);
var respnseText = await result.Content.ReadAsStringAsync();
}
How to post the following data to servlet url:
Data:
enc_request=63957FB55DD6E7B968A7588763E08B240878046EF2F520C44BBC63FB9CCE726209A4734877F5904445591304ABB2F5E598B951E39EAFB9A24584B00590ADB077ADE5E8C444EAC5A250B1EA96F68D22E44EA2515401C2CD753DBA91BD0E7DFE7341BE1E7B7550&access_code=8JXENNSSBEZCU8KQ&command=confirmOrder&request_type=XML&response_type=XML&version=1.1
Url:
"https://logintest.ccavenue.com/apis/servlet/DoWebTrans";
I tried https://social.msdn.microsoft.com/Forums/vstudio/en-US/df76fbfa-2931-4c9f-8671-785307243f62/post-request-to-a-java-servlet-and-process-httpresponse-using-net?forum=wcf . But I'm getting the error: C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send
Below is my code:
StringBuilder sbQueryString = new StringBuilder();
CCACrypto ccaCrypto = new CCACrypto();
string workingKey = "14A246E9D4341159638AC8EB776F3BE6";
//put in the 32bit alpha numeric key in the quotes provided here
sbQueryString.Append("enc_request=");
sbQueryString.Append(ccaCrypto.Encrypt(GenerateOrderXml(appointmentId), workingKey));
sbQueryString.Append("&");
sbQueryString.Append("access_code=");
sbQueryString.Append("AVQJ68DL46BW00JQWB");
sbQueryString.Append("&");
sbQueryString.Append("Command=");
sbQueryString.Append("cancelOrder");
sbQueryString.Append("&");
sbQueryString.Append("request_type=XML&response_type=XML");
sbQueryString.Append("&");
sbQueryString.Append("version=1.1");
//Response.Redirect("../ccAvenue/ccavAPIHandler.aspx?" + sbQueryString.ToString(), false);
//string url = "https://logintest.ccavenue.com/apis/servlet/DoWebTrans";
string url = "https://180.179.175.17/apis/servlet/DoWebTrans";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = sbQueryString.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();
// Display the status.
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.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
You can try simplifying your code by using a WebClient:
using (var client = new WebClient())
{
var data = new NameValueCollection
{
{ "enc_request", "63957FB55DD6E7B968A7588763E08B240878046EF2F520C44BBC63FB9CCE726209A4734877F5904445591304ABB2F5E598B951E39EAFB9A24584B00590ADB077ADE5E8C444EAC5A250B1EA96F68D22E44EA2515401C2CD753DBA91BD0E7DFE7341BE1E7B7550" },
{ "access_code", "8JXENNSSBEZCU8KQ" },
{ "command", "confirmOrder" },
{ "request_type", "XML" },
{ "response_type", "XML" },
{ "version", "1.1" },
};
var url = "https://logintest.ccavenue.com/apis/servlet/DoWebTrans";
byte[] result = client.UploadValues(url, data);
}
I have an application written in c#.NET 2.0 Windows app. I am trying to implement web crawler using HttpWebRequest & HttpWebResponse. In this application i am using both http get & post request for a third part web sites. this web site provides user account for its members.
i am trying to login this sites using positing data then entering into my profile page & then trying to make another GETrequest & then make another POST request with post data.
but i am not able to make successfull request .
it through an error
"The server committed a protocol violation. Section=ResponseHeader
Detail=Header name is invalid"
then i set <httpWebRequest useUnsafeHeaderParsing="true" /> in app.config files. after that
it throw an error The underlying connection was closed:
The connection was closed unexpectedly : System.Net.WebException.
anybody can tell me what the reason for showing this error
my code below.
request.CookieContainer = objContainer;
request.KeepAlive = true;
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
//=======================================================================
StringBuilder strLinkBuilder = new StringBuilder();
strLinkBuilder.Append("j_username=username");
strLinkBuilder.Append("&j_password=password");
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "j_security_check");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = strLinkBuilder.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add(response.Cookies);
// Get the request 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.
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
// Read the content.
strServerResponse = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
//-------------------------------------------------------
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "ded/nsdlconsofile.xhtml");
//request.CookieContainer = objContainer;
request.KeepAlive = true;
// request.Method = "POST";
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add(response.Cookies);
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
//-------------------------------------------------------
strLinkBuilder = new StringBuilder();
strLinkBuilder.Append("finYr=2012");
strLinkBuilder.Append("&qrtr=3");
strLinkBuilder.Append("&frmType=24Q");
strLinkBuilder.Append("&download_conso=Go");
strLinkBuilder.Append("&requestnsdlconsoForm_SUBMIT=1");
Dictionary<string, string> objNameval = TraceHiddenField(strServerResponse, "");
foreach (KeyValuePair<string, string> pair in objNameval)
{
strLinkBuilder.Append("&" + pair.Key + "=" + pair.Value);
}
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "ded/nsdlconsofile.xhtml");
// Set the Method property of the request to POST.
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = false;
// request.ServicePoint.Expect100Continue = false;
request.UserAgent = "Mozilla/4.0 (compatible;)";
request.ProtocolVersion = HttpVersion.Version10;
// Create POST data and convert it to a byte array.
postData = strLinkBuilder.ToString();
byte[] byteData = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteData.Length;
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add( response.Cookies);
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteData, 0, byteData.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
I am currently having a problem.
I am trying to post my data to a PHP document but it does not get the whole value.
Somewhere in the middle it stops posting.
Does anyone know where the problem is located?
The bytearray is 7401 long. That cant be to long rigth?
My code is below:
public string RecieveData(string url, string postData = "")
{
WebRequest request = WebRequest.Create(url);
// If required by the server, set the credentials.
NetworkCredential nc = new NetworkCredential("user", "pass");
Stream dataStream;
if (postData != "")
{
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.string postData = "This is a test that posts this string to a Web server.";
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.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
request.Credentials = nc;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(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.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
/*
}
catch (Exception)
{
MessageBox.Show("Er is iets fout gegaan met verbinden");
return "";
}
*/
}
7401 is not too long.
My guess is that the data you are posting are not fully URL-encoded, e.g. one of the characters in the byte array causes the PhP parser to stop. Make sure you are looking at the raw data (e.g. using Wireshark).
I got a Java Servelet like
http://152.252.271.12:9999/media/servlet/RequestProcessor.do
for this I need to pass parameters in Querystring like this
http://152.252.271.12:9999/media/servlet/RequestProcessor.do?input=abc
I need to read response back.
I tried like this.
request.Method = "POST";
request.KeepAlive = false;
request.Credentials = CredentialCache.DefaultCredentials;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
}
// Read Response.
HttpWebResponse webresponse = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(webresponse.GetResponseStream(), Encoding.Default))
{
result = reader.ReadToEnd();
logtxn.LogTxn(result, "SPDCL RESPONSE");
}
webresponse.Close();
Any help appreciated..
Use WebRequest & WebResponse classes. Check http://gsraj.tripod.com/dotnet/webgetpost.html for more information.
I've had a similar problem in the past, I had to host a service in IIS that accepted a string containing a request and returned another string with a response to that request. All of the above needed to be done using HTTP POST.
The solution I found was to host a WCF service on IIS and configure it to use HTTP GET/POST protocols.
Also I remember that I needed to use a Stream class to input and output data (a simple string would not work in this case), in other words, I had a HTTP POST method in WCF that was something like:
Stream GetData(Stream data);
Take a look at this article.
You can use the WebClient class, as a client for the servlet. For example
WebClient myWebClient = new WebClient();
// Download the Web resource and save it into a data buffer.
byte[] myDataBuffer = myWebClient.DownloadData (#"http://152.252.271.12:9999/media/servlet/RequestProcessor.do?input=abc");
// Display the downloaded data.
string download = Encoding.ASCII.GetString(myDataBuffer);
Now parse the result string download and obtain the response.
Please find the below code:
public class MyWebRequest
{
private WebRequest request;
private Stream dataStream;
private string status;
public String Status
{
get
{
return status;
}
set
{
status = value;
}
}
public MyWebRequest(string url)
{
// Create a request using a URL that can receive a post.
request = WebRequest.Create(url);
}
public MyWebRequest(string url, string method): this(url)
{
if (method.Equals("GET") || method.Equals("POST"))
{
// Set the Method property of the request to POST.
request.Method = method;
}
else
{
throw new Exception("Invalid Method Type");
}
}
public MyWebRequest(string url, string method, string data): this(url, method)
{
// Create POST data and convert it to a byte array.
string postData = data;
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.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
public string GetResponse()
{
// Get the original response.
WebResponse response = request.GetResponse();
this.Status = ((HttpWebResponse) response)
.StatusDescription;
// Get the stream containing all content returned by the requested server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content fully up to the end.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
}
//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest("http://www.yourdomain.com", "POST", "a=value1&b=value2");
//show the response string on the console screen.
Console.WriteLine(myRequest.GetResponse());