I need to do this from C #, it's a post that works ok from the web, but I don't know what I'm doing wrong.
I leave a picture of the F12 when I act on the web, I try to do the same in C # but I can't get it to work.
WebRequest request = WebRequest.Create("https://xxxxxxxxxxxxx");
var Token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
request.Headers.Add("accessToken", Token);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
var data = "lockId=xxxxx";
streamWriter.Write(data);
}
var response = (HttpWebResponse)request.GetResponse();
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
MessageBox.Show(result);
}
response.Close();
}
Related
I have a POST Method that passes the login credentials to the API. Once the login is successful I will need to perform a GET method to retrieve some data.
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
login = "myLogin",
password = "myPassword"
});
streamWriter.Write(json);
}
//Do I implement the GET request right here? Any advice is appreciated.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Response.Write(result);
}
I Should implement the get after
var result = streamReader.ReadToEnd();
I'm trying to log in into iCloud using a Json Post request in C#. Before trying to implement the code I was studying a little bit the iCloud requests using Chrome Console and using an Ad-on to replicate the requests in order to obtain the same result of the website.
First of All I checked the request directly from iCloud website:
And this is the response:
{
"serviceErrors" : [ {
"code" : "-20101",
"message" : "Il tuo IDĀ Apple o la password non sono corretti."
} ]
}
Using "Advance REST Client" ad Chrome plugin to replicate the request I ve tried the same Json request to the same Url. But I get Empty response:
I Also tried to copy and paste the whole Header (All the settings) and than send the request but the response is the same:
Anyone has an Advice?
UPDATE: I tried to implement A Json request through c# program:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{accountName: \"briesanji #gmail.com\", password: \"testPassword\", rememberMe: false, trustTokens: []}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
The problem is that Execution breaks when the
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
is hit and it gives me this error: System.Net.WebException: 'Error Remote Server: (400) Request not valid.'
UPDATE: I solved in this way:
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
Anyways I tested also the Answer and it was good to.. So I check it as valid thanks.
With this i dont get any error and the response content of the second request just tells me that there were too many failed logins for the test account...
private static void ICloud()
{
var cc = new CookieContainer();
var first = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf");
first.Method = "GET";
first.CookieContainer = cc;
var response1 = (HttpWebResponse)first.GetResponse();
using (var streamReader = new StreamReader(response1.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
var second = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
second.ContentType = "application/json";
second.Method = "POST";
second.Accept = "application/json";
second.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
second.Referrer = "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf";
second.Headers.Add("X-Requested-With", "XMLHttpRequest");
second.Headers.Add("X-Apple-Widget-Key", "83545bf919730e51dbfba24e7e8a78d2");
using (var streamWriter = new StreamWriter(second.GetRequestStream()))
{
string json = "{\"accountName\":\"test#icloud.com\",\"password\":\"test\",\"rememberMe\":false,\"trustTokens\":[]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var response2 = (HttpWebResponse)second.GetResponse();
using (var streamReader = new StreamReader(response2.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException we)
{
using (var r = new StreamReader(we.Response.GetResponseStream()))
{
var result2 = r.ReadToEnd();
}
}
}
I'm trying to convert this curl command to c#
curl -i 'http://developer.echonest.com/api/v4/artist/profile?api_key=[API KEY]&name=weezer'
This returns a response header with content like so:
HTTP/1.1 200 OK
Content-Length: 135
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 62
X-RateLimit-Used: 58
I tried this code but when I run it, it gets an exception: "HTTP Error 405 Method not allowed".
string baseurl = "http://developer.echonest.com/api/v4/artist/profile?api_key=[API KEY]&name=weezer";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl);
request.Method = "POST";
request.Accept = "application/json";
request.UserAgent = "curl/7.37.0";
request.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string data = "browser=Win7x64-C1|Chrome32|1024x768&url=http://www.google.com";
streamWriter.Write(data);
}
var response = request.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
Console.WriteLine(text);
}
Any help will be appreciated.
As well as the changes Daniel suggested, I would remove the UserAgent. After that, it looks pretty much like the C# I'm using successfully. Here's a somewhat shortened version of that:
string baseurl = "http://developer.echonest.com/api/v4/artist/profile?api_key=[API KEY]&name=weezer";
var req = (HttpWebRequest) WebRequest.Create(baseurl);
req.Method = WebRequestMethods.Http.Get;
req.Accept = "application/json";
using (var response = (HttpWebResponse) req.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
var stream = response.GetResponseStream();
if (stream != null)
{
using (var sr = new StreamReader(stream))
{
responseString = sr.ReadToEnd();
}
var remaining = GetRateInfo(response.Headers, "X-RateLimit-Remaining");
var used = GetRateInfo(response.Headers, "X-RateLimit-Used");
var limit = GetRateInfo(response.Headers, "X-RateLimit-Limit");
Trace.WriteLine($"Excedeed EchoNest Limits: remaining {remaining} - used {used} - limit {limit}");
}
}
else
{
// Error handling
}
// And the header parsing code:
private static int GetRateInfo(WebHeaderCollection headers, string type)
{
var s = headers.Get(type);
if (s == null)
return -1;
int info;
return int.TryParse(s, out info) ? info : -1;
}
I'm trying to convert curl request to WebRequest in C# but not able to get the response as it always returns 401 unauthorized error
Here is the working curl request:
curl -k -v https://api.demo.peertransfer.com/v1/transfers -H "Content-Type: application/json" -X POST -d "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}" -H "X-Peertransfer-Digest: zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI="
Output:
The result in the red box is what I need to get in WebRequest Response,
here is my C# code
private void testnewfunc()
{
string value = "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}";
var URI = new Uri("https://api.demo.peertransfer.com/v1/transfers");
byte[] data = System.Text.ASCIIEncoding.Default.GetBytes(value);
var requst = (HttpWebRequest)WebRequest.Create(URI);
requst.UserAgent = "curl/7.43.0";
requst.Method = "POST";
requst.KeepAlive = true;
requst.AllowAutoRedirect = true;
requst.ContentType = " application/json";
requst.ContentLength = data.Length;
// wc.Headers["Content-Type"] = "application/json";
requst.Accept = "*/*";
//Or any other encoding type.
string result = System.Convert.ToBase64String(data);
var uname = "hultdemo2015";
var pword = "gEejgC0GF8pCbI7C";
var creds = string.Format("{0}:{1}", uname, pword);
creds = Convert.ToBase64String(Encoding.ASCII.GetBytes(creds));
requst.Headers["Authorization"] = string.Format("{0} {1}", "Basic", creds);
requst.Headers["X-Peertransfer-Digest"] = string.Format("{0}", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
using (Stream stream = requst.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var httpResponse = (HttpWebResponse)requst.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
// return true;
}
}
Not sure what I'm making wrong in the WebRequest.
Here's my solution:
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
var message = new HttpRequestMessage(HttpMethod.Post, new Uri("https://api.demo.peertransfer.com/v1/transfers"));
message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
message.Headers.Add("X-Peertransfer-Digest", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
message.Content = new StringContent("{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}", Encoding.UTF8, "application/json");
var responseMessage = await client.SendAsync(message);
MessageBox.Show(string.Format("Status Code: {0}{1}Content-Type: {2}{1}Date: {3}{1}Location:{4}", responseMessage.StatusCode, Environment.NewLine, responseMessage.Content.Headers.ContentType, responseMessage.Headers.Date, responseMessage.Headers.Location));
And here's the response from the server (same as curl):
Version compatible with .Net 4.0
var data = "{\"provider\":\"HUL\",\"payment_destination\":\"hult-applicationfee\",\"amount\":\"29000\",\"callback_url\":\"http://studentapplication.local/en/nextsteps\",\"callback_id\":\"abc1234546asas\",\"dynamic_fields\":{\"student_id\":\"32453245\",\"student_first_name\":\"Candy\",\"student_last_name\":\"Student\"}}";
var request = (HttpWebRequest)WebRequest.Create(new Uri("https://api.demo.peertransfer.com/v1/transfers"));
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Accept = "*/*";
request.Headers.Add("X-Peertransfer-Digest", "zYUt+Pn0A06wsSbCrrbAZn68Aslq9CbSUAKBrUEwIzI=");
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var reqStream = request.GetRequestStream())
using (var writer = new StreamWriter(reqStream))
{
writer.Write(data);
}
var response = request.GetResponse();
MessageBox.Show(response.Headers.ToString());
Make sure you include these using statements:
using System.IO;
using System.Net;
and these are the response headers from the server:
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);
}