Response returning html code instead of XML - c#

I am sending XML data using HTTP POST to a specified URL.Expected response is to be in XML format. But I am receiving HTML code instead of XML.I am sending my sample post code.
string postData = null;
postData = "NETCONNECT_TRANSACTION=" + System.Web.HttpUtility.UrlEncode(xdoc.ToString());
HttpWebRequest experianRequest = (HttpWebRequest)WebRequest.Create("some url");
experianRequest.Method = "POST";
experianRequest.ContentType = "application/x-www-form-urlencoded";
string UserIDFormated = "username:password";
experianRequest.Headers.Add("Authorization: BASIC" + ConvertToBase64String(UserIDFormated));
experianRequest.Timeout = 100000;
experianRequest.KeepAlive = false;
experianRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteData;
byteData = encoding.GetBytes(postData);
experianRequest.AllowAutoRedirect = true;
experianRequest.ContentLength = byteData.Length;
Stream newStream = experianRequest.GetRequestStream();
newStream.Write(byteData, 0, byteData.Length);
newStream.Close();
HttpWebResponse experianResponse = (HttpWebResponse)experianRequest.GetResponse();
StreamReader reader = new StreamReader(experianResponse.GetResponseStream(), Encoding.UTF8);
//XmlTextReader objxml = new XmlTextReader(newStream2);
//XmlDocument xdocresponse = new XmlDocument();
//xdocresponse.Load(experianResponse.GetResponseStream());
//string root = xdocresponse.DocumentElement.OuterXml;
//XDocument xdocresponse = XDocument.Load(objxml);
//objxml.Close();
//experianResponse.Close();
//StreamReader reader = new StreamReader(newStream2);
string responseFromServer = reader.ReadToEnd();
reader.Close();
//newStream.Close();
experianResponse.Close();

Related

HTTPWebResponse Failed to stream the response when passing "Combination Of Special characters" as password in Parameters

Working Scenario
When Passing first parameter "strPostData" (Not contain special characters in password) as below xml request means works fine and StreamReader providing the response as well & variable "strResult" loaded successfully.. "Request=janajana"
NOT Working Scenario
But when user password contains "special characters" in first parameter "strPostData" means, StreamReader failed to provide the response & variable "strResult" not loaded successfully.. "Request=<request><Username>jana</Username><Password>jana!##$%^&*()</Password></request>"
When passing password with combination of "special characters" when HTTPWebResponse failed & Streamreader also gets failed..
I have tried with Stream object statement with ..
//string tempString = Encoding.UTF8.GetString(buffer, 0, buffer.Length); &
Read Buffer code change
//Int32 count = await streamRead.ReadAsync(readBuffer, 0, 256); but not works ,,, please guide me anyone
public string[] GetResponseWebAPI(string strPostData, string strUrl)
{
string[] arrReturn = new string[3];
HttpWebResponse myHttpWebResponse = null;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] buffer = encoding.GetBytes(strPostData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(strUrl);
myRequest.Timeout = 25000;// 25s
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = buffer.Length;
myRequest.AllowAutoRedirect = true;
ServicePointManager.ServerCertificateValidationCallback = new
System.Net.Security.RemoteCertificateValidationCallback
(AcceptAllCertifications);
Stream newStream = myRequest.GetRequestStream();
newStream.Write(buffer, 0, buffer.Length);
newStream.Close();
myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse();
WebHeaderCollection webHeader = myHttpWebResponse.Headers;
arrReturn[0] = webHeader["Statuscode"];
arrReturn[1] = webHeader["Statusmessage"];
Stream streamResponse = myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
Char[] readBuffer = new Char[256];
int count = streamRead.Read(readBuffer,0, 256);
string strResult = string.Empty;
while (count > 0)
{
strResult += new String(readBuffer,0, count);
count = streamRead.Read(readBuffer,0, 256);
}
arrReturn[2] = strResult;
streamRead.Close();
streamResponse.Close();
myHttpWebResponse.Close();
return arrReturn;
}
I think the problem is in
myRequest.ContentType = "application/x-www-form-urlencoded";
So, from this line you are saying that content is URL-encoded and should be escaped.
So I assume, as a quick fix you could change
byte[] buffer = encoding.GetBytes(strPostData);
to
byte[] buffer = encoding.GetBytes(WebUtility.UrlEncode(strPostData));
or something.
But I do believe this intention could be expressed better. So consider using HttpClient and FormUrlEncodedContent:
public string[] GetResponseWebAPI(string strPostData, string strUrl)
{
string[] arrReturn = new string[3];
ServicePointManager.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => true;
var handler = new HttpClientHandler()
{
AllowAutoRedirect = false
};
using (var client = new HttpClient(handler))
using (var content =
new FormUrlEncodedContent(new[] {new KeyValuePair<string, string>("Request", strPostData)}))
{
client.Timeout = TimeSpan.FromSeconds(25);
var response = client.PostAsync(strUrl, content).GetAwaiter().GetResult();
arrReturn[0] = response.Headers.GetValues("Statuscode").FirstOrDefault();
arrReturn[1] = response.Headers.GetValues("Statusmessage").FirstOrDefault();
arrReturn[2] = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
return arrReturn;
}

Getting error only when value is passed in json string in httpwebrequest

I am peforming HttpWebRequest to perform POST method. I get error only when I pass value otherwise It's working perfectly.
Code:
public void CreateOrganization(string accountname)
{
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
string parsedContent = "{\"name\":\" "+accountname+" \"}";
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
}
It stops working at Stream newStream = http.GetRequestStream(); .

upload file in box api with multipart/form-data in c#

I am trying to upload file in box using box api
its Give me Error is Bad Request
whats wrong in this code please help me
public static FileDetails PutFile(string token, byte[] filebytes, string FolderId, string filename, string filecontentType)
{
Encoding encoding = Encoding.UTF8;
FileDetails objFile = new FileDetails();
Stream formDataStream = new System.IO.MemoryStream();
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string boundry = formDataBoundary;
string contentType = "multipart/form-data;boundary=" + boundry;
try
{
//request.ContentLength = bytes.Length;
Attributes attributes = new Attributes();
attributes.name = Path.GetFileNameWithoutExtension(filename);
attributes.parent = new Parent();
attributes.parent.id = FolderId;
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
boundry,
"file",
filename,
filecontentType ?? "application/octet-stream");
formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
formDataStream.Write(filebytes, 0, filebytes.Length);
string jsonstring = new JavaScriptSerializer().Serialize(attributes);
string data = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\";\r\n{2}\r\n\r\n",
boundry,
"attributes",
jsonstring);
formDataStream.Write(encoding.GetBytes(data), 0, encoding.GetByteCount(data));
string footer = "\r\n--" + boundry + "--\r\n";
formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
var uri = "https://upload.box.com/api/2.0/files/content";
var request = (HttpWebRequest)WebRequest.Create(uri.ToString());
request.Method = "POST";
request.ContentType = contentType;
request.Headers.Add("Authorization", "Bearer " + token);
request.ContentLength = formData.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var accessToken = reader.ReadToEnd();
response.Close();
}
catch (WebException e)
{
var resp = new StreamReader(e.Response.GetResponseStream()).ReadToEnd();
}
return objFile;
}

How can i post a request with parameter from C#.net

I want to post a request on server using POST and webrequest?
I need to pass parameters as well while posting?
how can i pass the parameters while posting?
How can i do that???
Sample code...
string requestBody = string.Empty;
WebRequest request = WebRequest.Create("myursl");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
//request.ContentLength = byte sXML.Length;
//System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
//sw.Write(sXML);
//sw.Close();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
if (res != null)
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), true))
{
ReturnBody = sr.ReadToEnd();
StringBuilder s = new StringBuilder();
s.Append(ReturnBody);
sr.Close();
}
}
if (ReturnBody != null)
{
if (res.StatusCode == HttpStatusCode.OK)
{
//deserialize code for xml and get the output here
string s =ReturnBody;
}
}
NameValueCollection keyValues = new NameValueCollection();
keyValues["key1"] = "value1";
keyValues["key2"] = "value2";
using (var wc = new WebClient())
{
byte[] result = wc.UploadValues(url,keyValues);
}
you can try with this code
string parameters = "sample=<value>&other=<value>";
byte[] stream= Encoding.UTF8.GetBytes(parameters);
request.ContentLength = stream.Length;
Stream newStream=webRequest.GetRequestStream();
newStream.Write(stream,0,stream.Length);
newStream.Close();
WebResponse webResponse = request.GetResponse();

Uploading picture to picasa web

I m trying to upload a new photo to picasa using the API.
code not working
I am getting the following error:
Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.
My Code:
string imgPath = "C:\foo.png";
StreamReader reader = new StreamReader(imgPath);
string imgBin = reader.ReadToEnd();
reader.Close();
string id=""//picasa ID
string album = "";//album name
string url = String.Format("http://www.picasaweb.google.com/data/feed/api/user/{0}/album/{1}",id, album);
string auth = "";
Byte[] send = Encoding.UTF8.GetBytes(imgBin);
int length = send.Length;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "image/png";
req.ContentLength = length;
req.Headers.Add("Authorization", "GoogleLogin auth=" + auth);
req.Headers.Add("Slug", "test");
Stream stream = req.GetRequestStream();
stream.Write(send, 0, length);
stream.Close();
WebResponse response = req.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string res = reader.ReadToEnd();
reader.Close();
Thanks
The problem is most likely with how you are reading the image. Instead of reading it as a string, try writing it directly into the request stream, similar to the following:
using (Stream fileStream = new FileStream(imgPath, FileMode.Open, FileAccess.Read))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "image/png";
request.ContentLength = fileStream.Length;
request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + auth);
request.Headers.Add("Slug", "test");
using (Stream requestStream = request.GetRequestStream())
{
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
requestStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseStr = responseReader.ReadToEnd();
}
string username = form["UserName"].ToString(); // <-- ### USERNAME HERE ###
string password = form["Password"].ToString(); // <-- ### PASSWORD HERE ###
PicasaService picasaService = new PicasaService("Tester");
picasaService.setUserCredentials(username, password);
// 2. Create a test album
//
AlbumEntry entry = new AlbumEntry();
entry.Title.Text = "test-69";
entry.Summary.Text = "test-69";
AlbumAccessor access = new AlbumAccessor(entry);
PicasaEntry album = picasaService.Insert(new Uri(PicasaQuery.CreatePicasaUri(username)), entry);
access = new AlbumAccessor(album);
// 3. Upload a photo
picasaService.Insert(new Uri(PhotoQuery.CreatePicasaUri(username, access.Id)), System.IO.File.OpenRead("thumb-1.jpg"), "image/jpeg", "thumb-1.jpg");

Categories

Resources