I'm working with Yandex Disk API (http://api.yandex.com/disk/doc/dg/reference/propfind_space-request.xml).
Having trouble with adding property in the request body (quota-available-bytes and quota-used-bytes)
public static string SpaceInfo(string path)
{
// Authorization.
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("https://webdav.yandex.ru/");
webReq.Accept = "*/*";
webReq.Headers.Add("Depth: 0");
webReq.Headers.Add("Authorization: OAuth " + token);
webReq.Method = "PROPFIND";
// Adding data in body request.
string inputData = #"<D:propfind xmlns:D=""DAV:""><D:prop><quota-available-bytes/></D:prop></D:propfind>";
byte[] buffer = new ASCIIEncoding().GetBytes(inputData);
webReq.ContentType = "text/xml; encoding='utf-8";
webReq.ContentLength = buffer.Length;
try
{
HttpWebResponse resp = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string dinfo = sr.ReadToEnd();
return dinfo;
}
}
I don't get any response, maybe i can use another method? What should i do?
Thanks!
quota-available-bytes should use same namespace "D"
Related
I am facing trouble in making an HTTP post request to Paypal for Secure token to use Paypal's Hosted solution but I am getting this error:
Some required information is missing or incorrect. Please correct the fields below and try again.
Error: Invalid Merchant or Merchant doesn't exist!
This is my C# code throught which I am making HTTP calls:
string strNVP = "https://pilot-payflowpro.paypal.com?PARTNER=PayPal&USER=myUsername&VENDOR=myVendorName&PWD=myPassword&TRXTYPE=A&AMT=" + obj.CurrentPackagePrice + "&CREATESECURETOKEN=Y&SECURETOKENID=" + Guid.NewGuid().ToString("N");
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVP);
wrWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());
//and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();
string result = Server.UrlDecode(responseData);
string[] arrResult = result.Split('&');
Hashtable htResponse = new Hashtable();
string[] responseItemArray;
foreach (string responseItem in arrResult)
{
responseItemArray = responseItem.Split('=');
htResponse.Add(responseItemArray[0], responseItemArray[1]);
}
string responseResult = htResponse["RESULT"].ToString();
string response = htResponse["RESPMSG"].ToString();
///for Success response
if (responseResult == "0" && response == "Approved")
{
ViewBag.secureToken = htResponse["SECURETOKEN"].ToString();
ViewBag.secureTokenId = htResponse["SECURETOKENID"].ToString();
}
Kindly help me in this problem may b I have done some wrong in my code above also.
The issue was that I was unable to receive a Token and TokenID due to that this exception was arising and then I resolved my issue by making modifications in the above code so that the Paypal sends back a response with Token and TokenID which I used in iframe and its working perfect now.
var request = (HttpWebRequest)WebRequest.Create("https://pilot-payflowpro.paypal.com");
var postData = "PARTNER=PayPal&USER=myUser&VENDOR=myVendor&PWD=myPassword&TRXTYPE=A&AMT=50&CREATESECURETOKEN=Y&SECURETOKENID=" + Guid.NewGuid().ToString("N");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var responseData = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(responseData.GetResponseStream()).ReadToEnd();
string result = Server.UrlDecode(responseString);
string[] arrResult = result.Split('&');
Hashtable htResponse = new Hashtable();
string[] responseItemArray;
foreach (string responseItem in arrResult)
{
responseItemArray = responseItem.Split('=');
htResponse.Add(responseItemArray[0], responseItemArray[1]);
}
string responseResult = htResponse["RESULT"].ToString();
string response = htResponse["RESPMSG"].ToString();
///for Success response
if (responseResult == "0" && response == "Approved")
{
ViewBag.secureToken = htResponse["SECURETOKEN"].ToString();
ViewBag.secureTokenId = htResponse["SECURETOKENID"].ToString();
}
The above code is buggy and throws exceptions while receiving a response etc. So this code block is working good.
So I have an api that I want to call to. The first call is an ahoy call and in the body of the request I need to send the ship_type, piratename and my piratepass. I then want to read the response which has my treasure booty that i will use for later.
I'm able to do this with web request. but i feel like there is a better way to do it with webclient.
(way I currently do it in webrequest)
//Credentials for the Pirate api
string piratename = "IvanTheTerrible";
string piratepass= "YARRRRRRRR";
string URI = "https://www.PiratesSuperSecretHQ.com/sandyShores/api/respectmyauthority";
WebRequest wr = WebRequest.Create(URI);
wr.Method = "POST";
wr.ContentType = "application/x-www-form-urlencoded";
string bodyData = "ship_type=BattleCruiser&piratename=" + piratename + "&piratepass=" + piratepass;
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] byte1 = encoder.GetBytes(bodyData);
wr.ContentLength = byte1.Length;
//writes the body to the request
Stream newStream = wr.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
WebResponse wrep = wr.GetResponse();
string result;
using (var reader = new StreamReader(wrep.GetResponseStream()))
{
result = reader.ReadToEnd(); // do something fun...
}
Thanks in advance either way.
You can do with this simple code
Uri uri = new Uri("yourUri");
string data = "yourData";
WebClient client = new WebClient();
var result = client.UploadString(uri, data);
Remember that you can use UploadStringTaskAsync if you want to be async
You can try like below as well:
public String wcPost(){
Map<String, String> bodyMap = new HashMap();
bodyMap.put("key1","value1");
WebClient client = WebClient.builder()
.baseUrl("domainURL")
.build();
String responseSpec = client.post()
.uri("URI")
.headers(h -> h.setBearerAuth("token if any"))
.body(BodyInserters.fromValue(bodyMap))
.exchange()
.flatMap(clientResponse -> {
if (clientResponse.statusCode().is5xxServerError()) {
clientResponse.body((clientHttpResponse, context) -> {
return clientHttpResponse.getBody();
});
return clientResponse.bodyToMono(String.class);
}
else
return clientResponse.bodyToMono(String.class);
})
.block();
return responseSpec;
}
I'm trying to get html code of authorizated steam page, but I can't log in.
My code is
public string tryLogin(string EXP, string MOD, string TIME)
{
var rsa = new RSA();
string encryptedPass;
rsa.Exponent = EXP;
rsa.Modulus = MOD;
encryptedPass = rsa.Encrypt(Pass);
string reqString = "username=kasyjack&password=" + encryptedPass + "&emailauth=&kasyjackfriendlyname=&captchagid=&captcha_text=&emailsteamid=&rsatimestamp=" + TIME + "&remember_login=false";
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://store.steampowered.com/login/dologin/");
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.ContentLength = requestData.Length;
request.Host = "store.steampowered.com";
request.Method = "POST";
request.UserAgent = Http.ChromeUserAgent();
request.CookieContainer = _CookieCont;
using (Stream st = request.GetRequestStream())
st.Write(requestData, 0, requestData.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string RSAR = sr.ReadToEnd();
return RSAR;
}
but response message is
{"success":false,"requires_twofactor":false,"clear_password_field":true,"captcha_needed":false,"captcha_gid":-1,"message":"Incorrect login."}
So does anyone know, what's wrong with login? Need your help.
SteamBot repository on GitHub has a working example on how to login to Steam via their website: link to method.
Here is a diagram explaining the whole process(made by me):
i used following code to get the access token from code as below
String code = HttpContext.Current.Request["code"];
string redirecturl = HttpContext.Current.Request["url"];
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(url);
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type={5}";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
string param = string.Format(data, code,configurationInfo.oauthclientid , configurationInfo.oauthclientsecretid, redirect_uri_encode, grant_type, "offline");
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();
}
i am getting response as
The remote server returned an error: (400) Bad Request.
i do not know where i went wrong
waiting for your valuable comments
Google also provides a higher level library for accessing its services. I find it makes it much easier to work with its APIs.
http://code.google.com/p/google-api-dotnet-client/
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);
}