Sending PDF base64 using POST web request - api

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();

Related

Weird response from API at Litecoin exchange

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.

Google API HTTP 401 - Token invalid - AuthSub token has wrong scope

I'm struggling with google api for a few days while sending a post request to Google sites API via C# application.
First I redeem the authorization code from google's servers by a GET request:
https://accounts.google.com/o/oauth2/auth?
scope=email%20profile&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.mydomain/myHome&
redirect_uri=http://localhost&
response_type=code&
client_id= // CLIENT ID here...
access_type=online&
approval_prompt=auto
In the redirect uri I got the authorization code which I use to claim the
access token:
string RequestUrl;
RequestUrl = "https://www.googleapis.com/oauth2/v3/token";
WebRequest request = WebRequest.Create(RequestUrl);
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "code=4/aPJAhLvlGLxw1fjKDCOpEQjfoVtNDZYq7FzvrziUero#&" +
"client_id=//cilent id here&" +
"client_secret=client secret here&" +
"redirect_uri=http://localhost&" +
"grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
The response containing the token looks like that:
{
"access_token": "ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw",
"token_type": "Bearer",
"expires_in": 3600,
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjE2NWQ2MzcwZTgzOTI5YmE4Y2E4ZWU5OTMzZTExZjg2Yzg4YzAwNjUifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTA1OTc0NjQwMTUzNzU0NjU1MDE5IiwiYXpwIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJuaXIuazFAaGFpZmFuZXQub3JnLmlsIiwiYXRfaGFzaCI6Imc5MU5wOVRYS2JUaVEzcFpTM2Ewa1EiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXVkIjoiOTkwMzUxMjA1MzY4LXBudGYxZXNtaXQ3a3Zlbmg5cnRvbW5pMmdhMmY0N2ZsLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaGQiOiJoYWlmYW5ldC5vcmcuaWwiLCJpYXQiOjE0MzU4MjI2ODAsImV4cCI6MTQzNTgyNjI4MH0.CeaQ8S3GG-yeAwqjU1ixdB7ro2SVKp2QdVTXNWl6196oJeQU1LFLpZ9FtrpNEGSDKHXrO5zx0ldE52RYw8TwMKILUqqCHLOewVJQMjZ6tiPzt-b-qeUta6Op4Z9HerwkMK2sofl88G-XZ6jKc7gk1gGPVcATBU7x0-QPRhQxmDUzP7zceVeoOtBD8g7liVHakK9sA5RNonGt-N6SvzECqhSLss7kDuXc4dStnENhyv_9oTIpvVsQplE-cJz7fDHC7mkW7BfwsgKBE8XbruBz5-o3AG5RVGyUTYqDaoq9qr3_NqckiRISUS127scaYwcYPE22Q8L_2AnpfJU0vuxo6g"
}
And the final step is to call the google api using the access_token
this way:
HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create("https://sites.google.com/feeds/site/mydomain");
req.ContentType = "application/atom+xml";
req.Host = "sites.google.com";
req.Method = "POST";
req.Headers["Gdata-version"] = "1.4";
req.Headers["Authorization"] = "Bearer ya29.pAGX8f4e0ZyBazzq5rxWVS6lL1jRyj0_GCog5UEO3FiGT2h4cj10jee4ziAoA09vHRoVejN5p7Iw";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("<entry xmlns='http://www.w3.org/2005/Atom' xmlns:sites='http://schemas.google.com/sites/2008'><title>Source Site</title><summary>A new site to hold memories</summary><sites:theme>slate</sites:theme></entry>");
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
try
{
using (System.Net.WebResponse resp = req.GetResponse())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
string i = sr.ReadToEnd().Trim();
}
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
But at the end of this step I get a 401 http error.
Token invalid - AuthSub token has wrong scope
What am I doing wrong?
Thanks in advance
you are authenticating your users using the following scopes
scope=email%20profile&
The Sites Data API uses the following scope: https://sites.google.com/feeds/.

I got This Error While Implementing Push Notification using REST API::The remote server returned an error: (401) Unauthorized

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();

while uploading a file to dropbox getting an error with method

Am using below url to upload a file to dropbox using oauth and am getting an error
{"error": "Call requires one of the following methods: PUT, POST, got GET!"}
am passing httpmethod as PUT but still asking the error.
Signature am using to upload is
https://api-content.dropbox.com/1/files_put/dropbox/test?oauth_consumer_key=twcek2m7cxtantc&oauth_signature_method=PLAINTEXT&oauth_token=918v4lxg2w23car&oauth_version=1.0&oauth_signature=fbs34nykryouuj1%26rbbprgh95tjzf22
using this am getting the error
{"error": "Call requires one of the following methods: PUT, POST, got GET!"}
please tell me anyone what to do for resolve this error.
public FileSystemInfo UploadFile(string root, string path, string file)
{
var uri = new Uri(new Uri(DropboxRestApi.ApiContentServer),
String.Format("files_put/{0}/{1}",
root, UpperCaseUrlEncode(path)));
var oauth = new OAuth();
//var requestUri = oauth.DownloadSignRequest(uri, _consumerKey, _consumerSecret, "POST", _accessToken);
var requestUri = oauth.SignRequest(uri, _consumerKey, _consumerSecret, _accessToken, "PUT");
var request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = WebRequestMethods.Http.Post;
request.KeepAlive = true;
byte[] buffer;
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
int length = (int) fileStream.Length;
buffer = new byte[length];
fileStream.Read(buffer, 0, length);
}
request.ContentLength = buffer.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
}
// request.Method = "POST";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var json = reader.ReadToEnd();
return ParseJson<FileSystemInfo>(json);
}
I made a mistaken in saving path of the file where i want to upload it.
Give the same file name for save in path.
that's all.

How to send bytes image to service in windows phone 7?

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/