void SendPost()
{
var url = "http://{ipaddress}/Network/Records/Registration?fname=tt&lname=tt&username=dddddddd&password=tt";
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
string parametersString = "";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str);
// Write to the request stream.
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
I wrote above code for sending image as bytes.it's not giving any errors.but image was not uploading properly.
i am passing base64 string of image in below code.
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str);
Please tell me what was wrong.why image was not uploading properly?
See this: Photo upload with parameters to a PHP page
and this: http://nediml.wordpress.com/2012/05/10/uploading-files-to-remote-server-with-multiple-parameters/
Related
I have a task which I need to upload a pdf converted to base64 string to Http post. I tried it using refit before but I failed to upload it. Now, I am trying a difference approach.
I used the web request POST method, First I converted the PDF to base64 but on the part that I call the stream.write method, I'm having an error since the file is already converted to base64 string and the stream.write paramater is byte array.
Also, how can I add these to the body using web request?
"mime": "application/pdf",
"data": "base64-data="
string pdfBase64;
const string pdfFileName = "file.pdf";
using (var pdfStream = await FileSystem.OpenAppPackageFileAsync(pdfFileName))
{
using (var pdfReader = new StreamReader(pdfStream))
{
var fileContents = await pdfReader.ReadToEndAsync();
pdfBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileContents));
}
}
WebRequest request = WebRequest.Create("https://goodmorning-axa-dev.azure-api.net/upload");
request.Method = "POST";
request.ContentLength = pdfBase64.Length;
request.ContentType = "application/json";
request.Headers.Add("x-axa-api-key", apiKey);
Stream stream = request.GetRequestStream();
stream.Write(pdfBase64, 0, pdfBase64.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
Toast.MakeText(this, sr.ReadToEnd(), ToastLength.Short).Show();
sr.Close();
stream.Close();
I'm trying to send a POST request to the Livecoin API. I have ensured that every parameter and the encoding is correct, but I keep getting a weird response:
{"success":false,"exception": "Unknown currency pair [currencyPair={1}]|null"}
This is what I'm trying to post:
string response = PrivatePostQuery("exchange/buymarket", "currencyPair=BTC/USD&price=12&amount=12");
And this is the method:
public string PrivatePostQuery(string requestUrl, string parameters = "")
{
parameters = http_build_query(parameters);
string Sign = HashHMAC(this.Exchange.ExchangeConnection.ApiSecretKey, parameters).ToUpper();
string uri = this.Exchange.ExchangeConnection.ApiUrl + requestUrl + "?" + parameters;
byte[] bytes = Encoding.UTF8.GetBytes(parameters);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
request.Headers["Api-Key"] = this.Exchange.ExchangeConnection.ApiKey;
request.Headers["Sign"] = Sign;
Stream dataStream = request.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
try
{
WebResponse WebResponse = request.GetResponse();
dataStream = WebResponse.GetResponseStream();
StreamReader StreamReader = new StreamReader(dataStream);
return StreamReader.ReadToEnd();
}
catch (WebException ex)
{
return new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
}
I have succeeded getting tickers and my balance from the API, so the problem is not because of the signature or headers.
I have tried changing the request to upper / lower case, and adding the parameters as request headers, with and without them in URL.
Thanks for the help!
Ok so there was no problem at all, LiveCoin exchange doesn't work with BTC-USDT pair, only with BTC-USD. So the response was correct, even tough it was a bit messy.
I got an error While use this code. I give a proper credentials for Urban Airship.
WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
request.Credentials = new NetworkCredential(UrbanAirShip UserLogin, MasterKey);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
//WRITE JSON DATA TO VARIABLE D
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"]}";
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.
using (Stream dataStream = request.GetRequestStream())
{
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
}
// Get the response.
WebResponse response = request.GetResponse();
//Error "The remote server returned an error: (400) Bad Request"
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
using (var reader = new StreamReader(dataStream))
{
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
response.Close();
return true;
}
}
// 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 = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\"Device_Token\"]}";
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 = "xxxx"; //App Key From Urban Airship
string password = "xxxxx"; //Master Secret Key From Urban Airship
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 want to pass array of byte to WCF service from my windows phone app.The url is like below
"http:/serviceurl/Service1.svc/saverecord3?firstarray="
How can i do this?
Here a part of my code, which I am using to send post data to my server
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http:/serviceurl/Service1.svc/saverecord3");
req.Method = "POST";
req.ContentType = "text/xml; charset=utf-8"; //if your data is different, use a content type accordingly
string postData = #"firstarray=thedatatosend";
int length = arrayData.Length;
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(arrayData);
req.Headers[HttpRequestHeader.ContentLength] = byteArray.Length.ToString();
req.BeginGetRequestStream(ar =>
{
using (var requestStream = req.EndGetRequestStream(ar))
{
// Write the body of your request here
requestStream.Write(byteArray, 0, length);
}
req.BeginGetResponse(a =>
{
try
{
var response = req.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var streamRead = new StreamReader(responseStream))
{
// Get the response message here
string responseString = streamRead.ReadToEnd();
//Do whatever you want here, with the response
}
}
catch (Exception e)
{
}
}, null);
}, null);
I spent too much hours to overcome this, till now with no success
From my site which is developed in MVC im trying to send a login request to a remote site, for example, facebook.
From fiddler It seems that the following inputs are required charset_test, lsd, locale,email, pass.
lsd key seems to be the unique token
Here is my code
CookieContainer cookies = new CookieContainer()
private string GetToken()
{
Uri uri = new Uri("http://www.facebook.com");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string htmlText = reader.ReadToEnd();
HtmlDocument document = new HtmlDocument(); --> HtmlAgilePack object
document.LoadHtml(htmlText);
//Need to check xpath doesn't return null object
HtmlNode node = document.DocumentNode.SelectNodes("//input[#name='lsd']").First();
return node.Attributes["Value"].Value;
}
private void Login()
{
string postData = string.Format("charset_test=fixcharset_test&lsd={0} &locale=en_US&email=myemail&pass=mypass", HttpUtility.UrlEncode(GetToken()));
Uri uri = new Uri("http://www.facebook.com/login.php");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.Method = "POST";
request.AllowAutoRedirect = true;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
//After login to facebook suppose to
public string void AddFriend()
{
Uri uri = new Uri("http://www.facebook.com");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.CookieContainer = cookies;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string status = response.StatusDescription;
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseDat
}
Keep in mind, that facebook is just an example, Im aware of its API, Im trying to login to site with no API.
sadly, the response return a facebook page with a sorry message for unrecognizing my browser.
Any help will be more than appreciate.
Thanks,
Are you setting HTTP_USER_AGENT on your request?