I'm working on Xamarin.Android App. I have to consume rest API of content type x-www-form-urlencoded. I'm unable to call the Rest API Successfully, before this, I consumed many web services but I'm working on this type of API first time. I'm stuck in this.
I tried two ways to consume it:
public static string makePostEncodedRequest(string url, string jsonparams)
{
string ret = "";
var httpwebrequest = (HttpWebRequest)WebRequest.Create(url);
httpwebrequest.ContentType = "application/x-www-form-urlencoded";
//httpwebrequest.Accept = Config.JsonHeaderAJ;
httpwebrequest.Method = Methods.Post.ToString();
byte[] bytearray = Encoding.UTF8.GetBytes(jsonparams);
using (var streamWriter = new StreamWriter(httpwebrequest.GetRequestStream(), Encoding.ASCII))
{
streamWriter.Write(bytearray);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpwebrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
ret = streamReader.ReadToEnd();
}
return ret;
}
the next one is:
Dictionary<string, string> requestParams = new Dictionary<string, string ();
requestParams.Add("value=", data1);
requestParams.Add("&value=", data2);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
HttpResponseMessage response = client.PostAsync(Config.DomainURl + Config.StudentLoginUrl, new FormUrlEncodedContent(requestParams)).Result;
var tokne = response.Content.ReadAsStringAsync().Result;
}
i have used the following code for authenticating user in my project might help you.
public static async Task<UserData> GetUserAuth(UserAuth userauth)
{
bool asd= CheckNetWorkStatus().Result;
if (asd)
{
var client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri(UrlAdd);// ("http://192.168.101.119:8475/");
var postData = new List<KeyValuePair<string, string>>();
var dto = new UserAuth { grant_type = userauth.grant_type, password = userauth.password, username = userauth.username };
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("grant_type", userauth.grant_type));
nvc.Add(new KeyValuePair<string, string>("password", userauth.password));
nvc.Add(new KeyValuePair<string, string>("username", userauth.username));
var req = new HttpRequestMessage(HttpMethod.Post, UrlAdd + "token") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
string result = await res.Content.ReadAsStringAsync();
var userData = JsonConvert.DeserializeObject<UserData>(result);
userData.ErrorMessage = "true";
return userData;
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Incorrect Password";
return ud;
}
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Check Ur Connectivity";
return ud;
}
}
Related
How can I send a file and form data with the HttpClient?
I have two ways to send a file or form data. But I want to send both like an HTML form. How can I do that? Thanks.
This is my code:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var client = new HttpClient();
var requestContent = new MultipartFormDataContent();
filename = openFileDialog1.FileName;
array = File.ReadAllBytes(filename);
var imageContent = new ByteArrayContent(array);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("audio/*");
requestContent.Add(imageContent, "audio", "audio.wav");
var values = new Dictionary<string, string>
{
{ "token", "b53b99534a137a71513548091271c44c" },
};
var content = new FormUrlEncodedContent(values);
requestContent.Add(content);
var response = await client.PostAsync("localhost", requestContent);
var responseString = await response.Content.ReadAsStringAsync();
txtbox.Text = responseString.ToString();
}
Here's code I'm using to post form information and a csv file
using (var httpClient = new HttpClient())
{
var surveyBytes = ConvertToByteArray(surveyResponse);
httpClient.DefaultRequestHeaders.Add("X-API-TOKEN", _apiToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArrayContent = new ByteArrayContent(surveyBytes);
byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");
var response = await httpClient.PostAsync(_importUrl, new MultipartFormDataContent
{
{new StringContent(surveyId), "\"surveyId\""},
{byteArrayContent, "\"file\"", "\"feedback.csv\""}
});
return response;
}
This is for .net 4.5.
Note the \" in the MultipartFormDataContent. There is a bug in MultipartFormDataContent.
In 4.5.1 MultipartFormDataContent wraps the data with the correct quotes.
Update: This link to the bug no longer works since the have retired Microsoft Connect.
Here's code I'm using a method to send file and data from console to API
static async Task uploaddocAsync()
{
MultipartFormDataContent form = new MultipartFormDataContent();
Dictionary<string, string> parameters = new Dictionary<string, string>();
//parameters.Add("username", user.Username);
//parameters.Add("FullName", FullName);
HttpContent DictionaryItems = new FormUrlEncodedContent(parameters);
form.Add(DictionaryItems, "model");
try
{
var stream = new FileStream(#"D:\10th.jpeg", FileMode.Open);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(#"http:\\xyz.in");
HttpContent content = new StringContent("");
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "uploadedFile1",
FileName = "uploadedFile1"
};
content = new StreamContent(stream);
form.Add(content, "uploadedFile1");
client.DefaultRequestHeaders.Add("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.dsfdsfdsfdsfsdfkhjhjkhjk.vD056hXETFMXYxOaLZRwV7Ny1vj-tZySAWq6oybBr2w");
var response = client.PostAsync(#"\api\UploadDocuments\", form).Result;
var k = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
}
}
I used the following code to get a token value but error (The remote certificate is invalid according to the validation procedure.) returns Thanks for the guidance.
private static async Task<string> GetAccessToken()
{
using (var client = new HttpClient())
{
const string URL = "https://bime.net.iraneit.com:3023/BimeApiManager_Main/api/EITAuthentication/GetAppToken";
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ICollection<KeyValuePair<String, String>> postData = new Dictionary<String, String>();
postData.Add(new KeyValuePair<String, String>("appname", " "));
postData.Add(new KeyValuePair<String, String>("secret", " "));
FormUrlEncodedContent content = new FormUrlEncodedContent(postData);
var ttt = content;
var result = await client.PostAsync(URL, content);
var response = await client.PostAsync("appToken", content);
if (response.IsSuccessStatusCode)
{
string JString = await response.Content.ReadAsStringAsync();
object responseData = JsonConvert.DeserializeObject(JString);
return ((dynamic)responseData).access_token;
}
else
{
return null;
}
}
}
I am trying to make a PostAsync request with c#. The following is my code.
static void Main(string[] args)
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage getResponse = client.GetAsync("http://google.com").Result)
{
CheckStatusCode(getResponse);
String header = getResponse.Headers.ToString();
var content = CreateCollection(getResponse.Content);
var _stringHeaderContent = header + "\r" + content;
HttpContent _content = new StringContent(_stringHeaderContent, Encoding.UTF8);
Console.WriteLine(_content);
using (HttpResponseMessage postResponse = client.PostAsync("http://google.com",_content).Result)
{
Console.WriteLine(postResponse.Headers);
CheckStatusCode(postResponse);
Console.WriteLine(postResponse.Headers);
}
}
}
}
methods:
public static void CheckStatusCode(HttpResponseMessage response)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.ReasonPhrase));
else
Console.WriteLine("200");
}
public static String CreateCollection(HttpContent content)
{
var myContent = content.ReadAsStringAsync().Result;
HtmlNode.ElementsFlags.Remove("form");
string html = myContent;
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var input = doc.DocumentNode.SelectSingleNode("//*[#name='__Token']");
var token = input.Attributes["value"].Value;
//add all necessary component to collection
NameValueCollection collection = new NameValueCollection();
collection.Add("__Token", token);
collection.Add("returnURL", "");
collection.Add("Email", "11111111#hotmail.com");
collection.Add("Password", "1234");
String queryString = GenerateQueryString(collection);
return queryString;
}
public static string GenerateQueryString(NameValueCollection collection)
{
var array = (from key in collection.AllKeys
from value in collection.GetValues(key)
select string.Format("{0}={1}", WebUtility.UrlEncode(key), WebUtility.UrlEncode(value))).ToArray();
return string.Join("&", array);
}
The problem I am having with this code is nothing gets stored in _content. I am trying to make a postAsync request with the header and a part of the content joined. however when I make the postAsync request nothing is stored in _content. Therefore the request fails.
Can anyone explain to me how I can make a postAsync request with _stringHeaderContent?
Regards
This is the way how to use PostAsync:
...
var httpClient = new HttpClient();
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("a", "1"));
postData.Add(new KeyValuePair<string, string>("b", "2"));
var content = new FormUrlEncodedContent(postData);
var result = httpClient.PostAsync("http://127.0.0.1/a.php", content).Result;
...
I'm currently trying to make a todo list on Windows Phone 8, using the API from Wunderlist. However, I can't pass my credentials in the POST request. Here's my code:
public async Task<System.IO.TextReader> DoRequestAsync(WebRequest request)
{
var task = Task.Factory.FromAsync((cb, o) => ((HttpWebRequest)o).BeginGetResponse(cb, o), res =>
((HttpWebRequest)res.AsyncState).EndGetResponse(res), request);
var result = await task;
var response = result;
var stream = response.GetResponseStream();
var sr = new System.IO.StreamReader(stream);
return sr;
}
And:
public async Task<System.IO.TextReader> Login(string email, string password)
{
//User Credentials
WebClient client = new WebClient();
var parms = new Dictionary<string, string>();
parms.Add(email, password);
//Request
HttpWebRequest request = HttpWebRequest.CreateHttp(API_URL + "/login");
request.AllowReadStreamBuffering = true;
request.Method = HttpMethod.Post;
// This doesn't seem to work
request.Credentials = new NetworkCredential(email, password);
var tr = await DoRequestAsync(request);
return tr;
}
private string DictToString(Dictionary<string, string> dict)
{
StringBuilder builder = new StringBuilder();
foreach(KeyValuePair<string, string> kvp in dict)
{
builder.Append(kvp.Key + "=" + kvp.Value + "&");
}
return builder.ToString();
}
Appreciate the help
remove string with .credentials, as NetworkCredential is for NTLM/Kerberos, here is api with usual POST
before sending request add:
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write("email=" + HttpUtility.UrlEncode(email));
writer.Write("&password=" + HttpUtility.UrlEncode(password));
}
I'm trying to upload an audio track to the Soundcloud.com using C#.NET, but there aren't any resources for .NET anywhere. Could someone post a link or an example of how to upload an audio file to my Soundcloud.com account using .NET?
Thank you,
Arman
To upload an audio using soundcloud's REST API you need to take care of HTTP POST related issues (RFC 1867). In general, ASP.NET does not support sending of multiple files/values using POST, so I suggest you to use Krystalware library: http://aspnetupload.com/Upload-File-POST-HttpWebRequest-WebClient-RFC-1867.aspx
After that you need to send proper form fields to the https://api.soundcloud.com/tracks url:
Auth token (oauth_token)
Track Title (track[title])
The file (track[asset_data])
Sample code:
using Krystalware.UploadHelper;
...
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]", "private");
form.Add("oauth_token", this.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()))
{
lblInfo.Text = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
lblInfo.Text = ex.ToString();
}
The example code allows you to upload an audio file from the server (notice the Server.MapPath method to form path to the file) and to get a response in json format (reader.ReadToEnd)
Here is a code snippet to upload track via the SoundCloud API =>
using (HttpClient httpClient = new HttpClient()) {
httpClient.DefaultRequestHeaders.ConnectionClose = true;
httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MySoundCloudClient", "1.0"));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", "MY_AUTH_TOKEN");
ByteArrayContent titleContent = new ByteArrayContent(Encoding.UTF8.GetBytes("my title"));
ByteArrayContent sharingContent = new ByteArrayContent(Encoding.UTF8.GetBytes("private"));
ByteArrayContent byteArrayContent = new ByteArrayContent(File.ReadAllBytes("MYFILENAME"));
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(titleContent, "track[title]");
content.Add(sharingContent, "track[sharing]");
content.Add(byteArrayContent, "track[asset_data]", "MYFILENAME");
HttpResponseMessage message = await httpClient.PostAsync(new Uri("https://api.soundcloud.com/tracks"), content);
if (message.IsSuccessStatusCode) {
...
}
Here another way to get non expiring token and upload track to SoundCloud using C#:
public class SoundCloudService : ISoundPlatformService
{
public SoundCloudService()
{
Errors=new List<string>();
}
private const string baseAddress = "https://api.soundcloud.com/";
public IList<string> Errors { get; set; }
public async Task<string> GetNonExpiringTokenAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseAddress);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id","xxxxxx"),
new KeyValuePair<string, string>("client_secret","xxxxxx"),
new KeyValuePair<string, string>("grant_type","password"),
new KeyValuePair<string, string>("username","xx#xx.com"),
new KeyValuePair<string, string>("password","xxxxx"),
new KeyValuePair<string, string>("scope","non-expiring")
});
var response = await client.PostAsync("oauth2/token", content);
if (response.StatusCode == HttpStatusCode.OK)
{
dynamic data = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
return data.access_token;
}
Errors.Add(string.Format("{0} {1}", response.StatusCode, response.ReasonPhrase));
return null;
}
}
public async Task UploadTrackAsync(string filePath)
{
using (var client = new HttpClient())
{
client.BaseAddress=new Uri(baseAddress);
var form = new MultipartFormDataContent(Guid.NewGuid().ToString());
var contentTitle = new StringContent("Test");
contentTitle.Headers.ContentType = null;
form.Add(contentTitle, "track[title]");
var contentSharing = new StringContent("private");
contentSharing.Headers.ContentType = null;
form.Add(contentSharing, "track[sharing]");
var contentToken = new StringContent("xxxxx");
contentToken.Headers.ContentType = null;
form.Add(contentToken, "[oauth_token]");
var contentFormat = new StringContent("json");
contentFormat.Headers.ContentType = null;
form.Add(contentFormat, "[format]");
var contentFilename = new StringContent("test.mp3");
contentFilename.Headers.ContentType = null;
form.Add(contentFilename, "[Filename]");
var contentUpload = new StringContent("Submit Query");
contentUpload.Headers.ContentType = null;
form.Add(contentUpload, "[Upload]");
var contentTags = new StringContent("Test");
contentTags.Headers.ContentType = null;
form.Add(contentTags, "track[tag_list]");
var bytes = File.ReadAllBytes(filePath);
var contentFile = new ByteArrayContent(bytes, 0, bytes.Count());
contentFile.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(contentFile, "track[asset_data]", "test.mp3");
var response = await client.PostAsync("tracks", form);
}
}
}