I'm trying to connect Django API with c # but when I connect I face a problem in C#.
Django here I use as a server API and C# as a client.
Errors in C# are "CSRF is missing or incorrect".
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Net.Http;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
private static string json;
public static string url { get; private set; }
static void Main(string[] args)
{
/*
try
{
CookieContainer container = new CookieContainer();
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("http://127.0.0.1/api/");
request1.Proxy = null;
request1.CookieContainer = container;
using (HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse())
{
foreach (Cookie cookie1 in response1.Cookies)
{
//Console.WriteLine(response.IsSuccessStatusCode);
var csrf = cookie1.Value;
Console.WriteLine(csrf);
Console.WriteLine("name=" + cookie1.Name);
Console.WriteLine();
Console.Write((int)response1.StatusCode);
//PostRespone("http://localhost/api/multiplyfunction/");
}
}
}
catch (WebException e)
{
Console.WriteLine(e.Status);
}
/* HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/");
request.CookieContainer = Cookie; // use the global cookie variable
string postData = "100";
byte[] data = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebResponse response = (HttpWebResponse)request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();*/
WebClient csrfmiddlewaretoken = new WebClient();
CookieContainer cookieJar = new CookieContainer();
var request1 = (HttpWebRequest)HttpWebRequest.Create("http://localhost/api/");
request1.CookieContainer = cookieJar;
var response1 = request1.GetResponse();
string baseSiteString = csrfmiddlewaretoken.DownloadString("http://localhost/api/");
// string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
// wc.Headers.Add("X-CSRF-Token", csrfToken);
csrfmiddlewaretoken.Headers.Add("X-Requested-With", "XMLHttpRequest");
using (HttpWebResponse response2 = (HttpWebResponse)request1.GetResponse())
{
foreach (Cookie cookie1 in response2.Cookies)
{
//string cookie = csrfmiddlewaretoken.ResponseHeaders[HttpResponseHeader.SetCookie];//(response as HttpWebResponse).Headers[HttpResponseHeader.SetCookie];
Console.WriteLine(baseSiteString);
//Console.WriteLine("CSRF Token: {0}", csrfToken);
//Console.WriteLine("Cookie: {0}", cookie);
//
csrfmiddlewaretoken.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
//wc.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
var csrf1 = cookie1.Value;
string ARG1 = ("100");
string ARG2 = ("5");
string ARG = ("ARG");
string csrfmiddlewaretoken1 =cookie1.Name +"="+cookie1.Value;
csrfmiddlewaretoken.Headers.Add(HttpRequestHeader.Cookie, csrfmiddlewaretoken1);
//string csrf = string.Join(cookie, ARG1, ARG2);
//string dataString =cookie;
// string dataString = #"{""user"":{""email"":"""+uEmail+#""",""password"":"""+uPassword+#"""}}";
string dataString = "{\"ARG1\": \"100\", \"ARG2\": \"5\"}";
// string dataString = "csrftokenmiddlewaretoken="+csrfmiddlewaretoken;
//dataString += "&ARG1=10";
//dataString += "&ARG2=10";
byte[] dataBytes = Encoding.ASCII.GetBytes(dataString);
//byte[] respon2 = csrfmiddlewaretoken.DownloadData(new Uri("http://localhost/api/statusfunction/"));
WebRequest request = WebRequest.Create("http://localhost/api/statusfunction/?ARG");
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 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);
byte[] responseBytes = csrfmiddlewaretoken.UploadData(new Uri("http://localhost/api/multiplyfunction/"), "POST", dataBytes);
string responseString = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responseString);
// byte[] res = csrfmiddlewaretoken.UploadFile("http://localhost/api/multiplyfunction/", #"ARG1:100");
// Console.WriteLine(result);
Console.WriteLine("value=" + cookie1.Value);
Console.WriteLine("name=" + cookie1.Name);
Console.WriteLine();
Console.Write((int)response2.StatusCode);
// PostRespone("http://localhost/api/multiplyfunction/");
}
}
}
}
}
Do you accept POST requests in your Django view? If yes, you should use #csrf_exempt decorator for the view that handles POST requests. The other option is to provide CSRF token from C# side.
Related
I am new to JSON and C# and trying to write a code that will perform an http web request POST to get a token. Below is my code but I keep getting 400 bad request. Probably my codes just incorrect and I will appreciate for any helps on this. Below is my codes :
static public string GetAuthorizationToken()
{
string token = string.Empty;
string requestUrl = "some URL";
HttpWebRequest httpWebRequest = WebRequest.Create(requestUrl) as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "x-www-form-urlencoded";
Dictionary<string, string> postParameters = new Dictionary<string, string>();
postParameters.Add("grant", "some credentials");
postParameters.Add("id", "1234123411");
postParameters.Add("secret", "1234123411");
postParameters.Add("scope", "abcd");
string postData = "";
foreach (string key in postParameters.Keys)
{
postData += WebUtility.UrlEncode(key) + "="
+ WebUtility.UrlEncode(postParameters[key]) + "&";
}
byte[] data = Encoding.ASCII.GetBytes(postData);
httpWebRequest.ContentLength = data.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
TokenResponse tokenResponse = new TokenResponse();
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
DataContractJsonSerializer responseSerializer = new DataContractJsonSerializer(typeof(TokenResponse));
Stream responseStream = response.GetResponseStream();
object objResponse = responseSerializer.ReadObject(responseStream);
tokenResponse = objResponse as TokenResponse;
response.Close();
if (tokenResponse != null)
{
return tokenResponse.accessToken;
}
}
return token;
}
Here is a precise and accurate example of a POST request and reading the response(though without serializing the JSON data). Only mistake I see so far in your code is an incorrect ContentType also we can't see what url you are trying to send the server(but odds are that it is incorrect). Hope it helps you advance.
using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
namespace SExperiment
{
class MainClass
{
public static void Main(string[] args)
{
try{
string webAddr="http://gurujsonrpc.appspot.com/guru";
var httpWebRequest = WebRequest.CreateHttp(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"method\" : \"guru.test\", \"params\" : [ \"Guru\" ], \"id\" : 123 }";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
//Now you have your response.
//or false depending on information in the response
}
}catch(WebException ex){
Console.WriteLine(ex.Message);
}
}
}
}
You have set requestUrl to "some URL". Please try with a web address that exists, in addition to changing the content type to "application/json".
I am tring to pull categories from my store on BigCommerce via API.
When I try my credentials at API Console;
https://developer.bigcommerce.com/console
it is working fine, but I when send credentials via C# post request it does not work.
I am receiving [{"status":401,"message":"No credentials were supplied in the request."}]
My code is like;
List<PostCredential> postCredentials = new List<PostCredential>();
postCredentials.Add(new PostCredential { name = "store_url", value = ApiPath });
postCredentials.Add(new PostCredential { name = "username", value = Username });
postCredentials.Add(new PostCredential { name = "api_key", value = ApiToken });
JavaScriptSerializer serializer = new JavaScriptSerializer();
string serialize = serializer.Serialize(postCredentials);
const string requestUrl = "https://myteststore1234.mybigcommerce.com/api/v2/categories.json";
StringBuilder postData = new StringBuilder();
postData.Append(serialize);
string postRequest = PostRequest(requestUrl, postData.ToString());
public static string PostRequest(string url, string postData)
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
string responseString = new StreamReader(responseStream).ReadToEnd();
return responseString;
}
return null;
}
is there any workaround for this?
WebHeaderCollection wHeader = new WebHeaderCollection();
wHeader.Clear();
//wHeader.Add("username:test");
//wHeader.Add("password:4afe2a8a38fbd29c32e8fcd26dc51f6d9b5ab99b");
//wHeader.Add("u","test:4afe2a8a38fbd29c32e8fcd26dc51f6d9b5ab99b");
string Username = "test";
string ApiToken = "4afe2a8a38fbd29c32e8fcd26dc51f6d9b5ab99b";
string sUrl = "https://store-bwvr466.mybigcommerce.com/api/v2/brands.json"; //txtstoreurl.Text.ToString() + "/api/v2/products.json";
HttpWebRequest wRequest = (HttpWebRequest)System.Net.HttpWebRequest.Create(sUrl);
wRequest.Credentials = new NetworkCredential(Username, ApiToken);
wRequest.ContentType = "application/json"; //' I don't know what your content type is
//wRequest.Headers = wHeader;
wRequest.Method = "GET";
HttpWebResponse wResponse = (HttpWebResponse)wRequest.GetResponse();
string sResponse = "";
using (StreamReader srRead = new StreamReader(wResponse.GetResponseStream()))
{
sResponse = srRead.ReadToEnd();
MessageBox.Show(sResponse);
}
After some research I found out I need to pass parameters like this;
httpWReq.Method = "GET";
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
httpWReq.Credentials = new NetworkCredential(Username, ApiToken);
I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Guyz facing problems with creating a push notification service (for android) using Google C2DM which uses OAuth 2.0 . I am sort of newbie dev , and the deadline is on the head ! Please help !
In the above question there was only one issue . I had lost my cool and was into tremendous pressure. This doesn't work well with intellectual property. So , with a bit of mental peace above simple issue was solved.
Guyz below given is the code for the dummies like me :
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.IO;
using System.Collections;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Configuration;
using System.Web.Script.Serialization;
using PushNotification.Entities;
namespace PushNotification
{
public class AndroidCommunicationService
{
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
public string GetAuthenticationCode()
{
string returnUrl = "";
string URL = "https://accounts.google.com/o/oauth2/auth";
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("response_type", "code");
postFieldNameValue.Add("scope", "https://android.apis.google.com/c2dm/send");
postFieldNameValue.Add("client_id", ConfigurationManager.AppSettings["ClientId"].ToString());
postFieldNameValue.Add("redirect_uri", "http://localhost:8080/TestServer/test");
postFieldNameValue.Add("state", "profile");
postFieldNameValue.Add("access_type", "offline");
postFieldNameValue.Add("approval_prompt", "auto");
postFieldNameValue.Add("additional_param", DateTime.Now.Ticks.ToString());
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Stream dataStream = Request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Request.Method = "POST";
try
{
WebResponse Response = Request.GetResponse();
var sr = new StreamReader(Response.GetResponseStream());
// You can do this and return the content on the screen ( I am using MVC )
returnUrl = sr.ReadToEnd();
// Or
returnUrl = Response.RedirectUri.ToString();
}
catch
{
throw ;
}
return returnUrl;
}
public TokenResponse GetNewToken(string Code)
{
TokenResponse tokenResponse = new TokenResponse();
string URL = ConfigurationManager.AppSettings["TokenCodeUrl"];
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("code", Code);
postFieldNameValue.Add("client_id", ConfigurationManager.AppSettings["ClientId"]);
postFieldNameValue.Add("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
postFieldNameValue.Add("redirect_uri", ConfigurationManager.AppSettings["RedirectUrl"]);
postFieldNameValue.Add("grant_type", "authorization_code");
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Stream dataStream = Request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Request.Method = "POST";
try
{
WebResponse Response = Request.GetResponse();
var tokenStreamRead = new StreamReader(Response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = tokenStreamRead.ReadToEnd();
tokenResponse = (TokenResponse)js.Deserialize(objText, typeof(TokenResponse));
}
catch (WebException wex)
{
var sr = new StreamReader(wex.Response.GetResponseStream());
Exception ex = new WebException(sr.ReadToEnd() + wex.Message);
throw ex;
}
return tokenResponse;
}
public TokenResponse RefreshToken(string RefreshToken)
{
TokenResponse tokenResponse = new TokenResponse();
string URL = ConfigurationManager.AppSettings["TokenCodeUrl"];
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("refresh_token", RefreshToken);
postFieldNameValue.Add("client_id", ConfigurationManager.AppSettings["ClientId"]);
postFieldNameValue.Add("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
postFieldNameValue.Add("grant_type", "refresh_token");
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL);
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
Stream dataStream = Request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Request.Method = "POST";
try
{
WebResponse Response = Request.GetResponse();
var tokenStreamRead = new StreamReader(Response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = tokenStreamRead.ReadToEnd();
tokenResponse = (TokenResponse)js.Deserialize(objText, typeof(TokenResponse));
}
catch
{
throw;
}
return tokenResponse;
}
public string SendPushMessage(string RegistrationId, string Message ,string AuthString)
{
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["PushMessageUrl"]);
Request.Method = "POST";
Request.KeepAlive = false;
//-- Create Query String --//
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("registration_id", RegistrationId);
postFieldNameValue.Add("collapse_key", "fav_Message");
postFieldNameValue.Add("data.message", Message);
postFieldNameValue.Add("additional_value", DateTime.Now.Ticks.ToString());
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
// This is to be sent as a header and not as a param .
Request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + AuthString);
try
{
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
return "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
return "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
return responseLine;
}
catch
{
throw;
}
}
private string GetPostStringFrom(NameValueCollection postFieldNameValue)
{
//throw new NotImplementedException();
List<string> items = new List<string>();
foreach (String name in postFieldNameValue)
items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(postFieldNameValue[name])));
return String.Join("&", items.ToArray());
}
private static bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
{
return true;
}
}
}
public class TokenResponse
{
public String access_token{ get; set; }
public String expires_in { get; set; }
public String token_type { get; set; }
public String refresh_token { get; set; }
}
Here's my code for Request and Response.
System.IO.MemoryStream xmlStream = null;
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url);
xmlStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(format));
byte[] buf2 = xmlStream.ToArray();
System.Text.UTF8Encoding UTF8Enc = new System.Text.UTF8Encoding();
string s = UTF8Enc.GetString(buf2);
string sPost = "XMLData=" + System.Web.HttpUtility.UrlDecode(s);
byte[] bPostData = UTF8Enc.GetBytes(sPost);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
HttpReq.Timeout = 30000;
request.Method = "POST";
request.KeepAlive = true;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bPostData, 0, bPostData.Length);
requestStream.Close();
}
string responseString = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
No part of this code crashes. The "format" string is the one with XML in it. By the end when you try to see what's in the responseString, it's an empty string. I am supposed to see the XML sent back to me from the URL. Is there something missing in this code?
I would recommend a simplification of this messy code:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "XMLData", format }
};
byte[] resultBuffer = client.UploadValues(url, values);
string result = Encoding.UTF8.GetString(resultBuffer);
}
and if you wanted to upload the XML directly in the POST body you shouldn't be using application/x-www-form-urlencoded as content type. You probably should specify the correct content type, like this:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "text/xml";
var data = Encoding.UTF8.GetBytes(format);
byte[] resultBuffer = client.UploadData(url, data);
string result = Encoding.UTF8.GetString(resultBuffer);
}