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);
}
Related
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
I want to target this string type "application/json" for urban airship api. Can you guys help me whats wrong with my string and structure?
string postData = "{"audience":"all","device_types":["android"],"notification":{"alert":"This is a broadcast."}}";
I did tried adding back slash "\" example below:
string postData = "{\"audience\":\"all\",\"device_types\":[\"android\"],\"notification\":{\"alert\":\"This is a broadcast.\"}}";
Below are my full code:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "{'audience':'all','device_types':'['android']','notification': {'alert':'This is a broadcast.'}";
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;
//Do a http basic authentication somehow
string username = "Zx5EPSG7Qhu-BvYtz0laTg";
string password = "sIaj2CjASlm27pimHqOfhA";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri("https://go.urbanairship.com/api/push/"), "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
// 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();
I got below error:
400 Bad Request – The request body was invalid, either due to malformed JSON or a data validation error. See the response body for more detail.
This should work:
{
"audience" : "all",
"device_types" : ["android"],
"notification" : {
"alert" : "This is a broadcast."
}
}
You have small type in the first value, an additional ' sign after "all":
{
"audience": "all"',
"device_types": [
"android"
],
"notification": {
"alert": "This is a broadcast."
}
}
In future, you can use online validators for such cases, like JSONLint.
I have utilities that post standard XML, but am faced with interacting with a server that requires something I'm not familiar with.
The expected XML format is like this:
"xmldata=<txn><element_1>element_1_value</element_1><element_2>element_2_value</element_2></txn>"
When I post using my standard method:
byte[] data = Encoding.ASCII.GetBytes(XDocumentToString(xml));
var client = new WebClient();
client.Headers.Add("Content-Type", "text/xml");
byte[] result = client.UploadData(new Uri(url), "POST", data);
string resultString = Encoding.ASCII.GetString(result);
return XDocument.Parse(resultString);
I get an error message about the XML not being formatted correctly.
When I use some stuff I've found:
var request = _requestFactory.CreateCreditCardSaleRequest(xmlStringFromAbove);
WebRequest webRequest = WebRequest.Create("https://domain.com/process_some_xml.do");
webRequest.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(request);
// Set the ContentType property of the WebRequest.
webRequest.ContentType = "text/xml; encoding='utf-8'";
// Set the ContentLength property of the WebRequest.
webRequest.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = webRequest.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 = webRequest.GetResponse();
// Display the status.
var httpWebResponse = (HttpWebResponse) response;
Console.WriteLine(httpWebResponse.StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
the response seems to indicate success, but no response content as expected.
I suspect it has something to do with the "xmldata=" at the beginning of the request, but cannot be sure.
Any suggestions?
Judging from the xmldata=, it sounds like the API wants the data sent as form-urlencoded. I suggest trying this:
string dataStr = "xmldata=" + HttpUtility.UrlEncode(XDocumentToString(xml));
byte[] data = Encoding.ASCII.GetBytes(dataStr);
and this:
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
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).