Add track to playlist SoundCloud API - api

In my Windows Phone App, I'm using the following code to add a track to playlist (i.e. a PUT request to playlists/id endpoint)
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(AccessToken);
HttpResponseMessage response = await httpClient.PutAsync(endpoint, new StringContent(data));
response.EnsureSuccessStatusCode();
}
where "data" is JSON data the form:
{"playlist":{"tracks":["TrackId(to be added)"]}}
The above code returns "OK"(200) response but the track is NOT added to the playlist!
What am I doing wrong? Stuck on it for two days. Thanks in advance!

I use Put to replace track ids in set.
here is sample code
for (String s : trackIds)
nameValuePairs.add(new BasicNameValuePair("playlist[tracks][][id]", s.trim()));
String url = "https://api.soundcloud.com/playlists/" + setId + ".json";
httpPut(url, nameValuePairs);

The problem was that the JSON data (of the request body) was not formatted correctly.
"data" must be of the form:
{"playlist":{"tracks":[{"id":"__"}, {"id":"__"}, {"id":"__"}]}}
Here the id-value pair must be present for
every track already present in the playlist, as well as
the track that you want to add to the playlist
(Remember, this is a PUT request. So, you need to update data i.e. update the "tracks" property of the "playlist")

Related

How to get string from httpclient request

I tried to get twitch api information but request dosent show anything
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.twitch.tv/helix/streams?game_id=33214"))
{
request.Headers.TryAddWithoutValidation("Client-ID", "ozzdg2w66nugbxdhrzzy5d7z");
var response = await httpClient.SendAsync(request);
}
}
I would use api request to get output precise number, but twitch channel names are not working anymore and you need channel ID which are private.
Basically what I need are 3 things:
Is channel live (true/false)
Live viewership count
thumbnail picture
Is there a way get those data? Or I need to know the secret ID?
I didn't get the conection between your topic and the description of your problem.
But if you want to request stream information you have to use the right endpoint url.
Like: https://api.twitch.tv/helix/streams?user_login=USER_NAME
For more information read the reference documentation https://dev.twitch.tv/docs/api/reference/#get-streams

ASP.net - Uploading Files Associated with a Database Record?

I know that there are tons of examples of multi-part form data uploading in ASP.net. However, all of them just upload files to the server, and use System.IO to write it to server disk space. Also, the client side implementations seem to handle files only in uploading, so I can't really use existing upload plugins.
What if I have an existing record and I want to upload images and associate them with the record? Would I need to write database access code in the upload (Api) function, and if so, how do I pass that record's PK with the upload request? Do I instead upload the files in that one request, obtain the file names generated by the server, and then make separate API calls to associate the files with the record?
While at it, does anyone know how YouTube uploading works? From a user's perspective, it seems like we can upload a video, and while uploading, we can set title, description, tags, etc, and even save the record. Is a record for the video immediately created before the API request to upload, which is why we can save info even before upload completes?
Again, I'm not asking HOW to upload files. I'm asking how to associate uploaded files with an existing record and the API calls involved in it. Also, I am asking for what API calls to make WHEN in the user experience when they also input information about what they're uploading.
I'm assuming you're using an api call to get the initial data for displaying a list of files or an individual file. You would have to do this in order to pass the id back to the PUT method to update the file.
Here's a sample of the GET method:
[HttpGet]
public IEnumerable<FileMetaData> Get()
{
var allFiles = MyEntities.Files.Select(f => new FileMetaData()
{
Name = f.Name,
FileName = f.FileName,
Description = f.Description,
FileId = f.Id,
ContentType = f.ContentType,
Tags = f.Tags,
NumberOfKB = f.NumberOfKB
});
return allFiles;
}
Here's a sample of the POST method, which you can adapt to be a PUT (update) instead:
[HttpPost]
[ValidateMimeMultipartContentFilter]
public async Task<IHttpActionResult> PutFile()
{
try
{
var streamProvider =
await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());
//We only allow one file
var thisFile = files[0];
//For a PUT version, you would grab the file from the database based on the id included in the form data, instead of creating a new file
var file = new File()
{
FileName = thisFile.FileName,
ContentType = thisFile.ContentType,
NumberOfKB = thisFile.ContentLength
};
//This is the file metadata that your client would pass in as formData on the PUT / POST.
var formData = streamProvider.FormData;
if (formData != null && formData.Count > 0)
{
file.Id = formData["id"];
file.Description = formData["description"];
file.Name = formData["name"] ?? string.Empty;
file.Tags = formData["tags"];
}
file.Resource = thisFile.Data;
//For your PUT, change this to an update.
MyEntities.Entry(file).State = EntityState.Detached;
MyEntities.Files.Add(file);
await MyEntities.SaveChangesAsync();
//return the ID
return Ok(file.Id.ToString());
}
I got the InMemoryMultipartFormDataStreamProvider from this article:
https://conficient.wordpress.com/2013/07/22/async-file-uploads-with-mvc-webapi-and-bootstrap/
And adapted it to fit my needs for the form data I was returning.

Wicket 6 - Capturing HttpServletRequest parameters in Multipart form?

USing Wicket 6.17 and servlet 2.5, I have a form that allows file upload, and also has ReCaptcha (using Recaptcha4j). When the form has ReCaptcha without file upload, it works properly using the code:
final HttpServletRequest servletRequest = (HttpServletRequest ) ((WebRequest) getRequest()).getContainerRequest();
final String remoteAddress = servletRequest.getRemoteAddr();
final String challengeField = servletRequest.getParameter("recaptcha_challenge_field");
final String responseField = servletRequest.getParameter("recaptcha_response_field");
to get the challenge and response fields so that they can be validated.
This doesn't work when the form has the file upload because the form must be multipart for the upload to work, and so when I try to get the parameters in that fashion, it fails.
I have pursued trying to get the parameters differently using ServletFileUpload:
ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory(new FileCleaner()) );
String response = IOUtils.toString(servletRequest.getInputStream());
and
ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory(new FileCleaner()) );
List<FileItem> requests = fileUpload.parseRequest(servletRequest);
both of which always return empty.
Using Chrome's network console, I see the values that I'm looking for in the Request Payload, so I know that they are there somewhere.
Any advice on why the requests are coming back empty and how to find them would be greatly appreciated.
Update: I have also tried making the ReCaptcha component multipart and left out the file upload. The result is still the same that the response is empty, leaving me with the original conclusion about multipart form submission being the problem.
Thanks to the Wicket In Action book, I have found the solution:
MultipartServletWebRequest multiPartRequest = webRequest.newMultipartWebRequest(getMaxSize(), "ignored");
// multiPartRequest.parseFileParts(); // this is needed since Wicket 6.19.0+
IRequestParameters params = multiPartRequest.getRequestParameters();
allows me to read the values now using the getParameterValue() method.

Sending JSON data to rest api

I have started to learn about REST API. So far I have been able to call my REST API post data using the form and also to get values from my REST API. Now I am trying to learn to send my data to my REST API using JSON object. I have been searching on the net and reading on StackOverflow on how to implement it but so far there is no luck. I am looking for some basic code examples where I can get an idea of how it's done. If some could help me with some codes on how to send data to my REST API using JSON and also how to retrieve that JSON data in my REST API it will be very helpful to me in learning REST API(Just the basic codes I hope it shouldn't take much of your time to post some codes). Btw I am using Jersey to implement my REST API. Thanks in Advance :) It really will be helpful to me in understanding sending JSON data to my web service Thanks again :)
The language is JAVA(JAX-RS implemented in Jersey)
While sending data in json request, your request should be in the form of a map (key value pair ). Key should be your attribute name and values as the value for the attribute.
For example if you are trying to find a employee using employeeid the your request should be of the form {data:{"employeeid":"1"}}
Be more specif about which platform you are using to call the RESTservice.
Hope this will help you.
var clientCreateOrder = new RestClient("#######################");
var requestCreateOrder = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
//Use below code for creating and sending dynamic json objects to RESTAPI
object[] purchase_units_arr = new object[1];
purchase_units_arr[0] = new
{
amount = new
{
currency_code = "USD",
value = "100.00"
}
};
var body = new
{
intent = "CAPTURE",
purchase_units = purchase_units_arr,
};
//Serialize Json object
request.AddParameter("undefined", new JavaScriptSerializer().Serialize(body).ToString(), ParameterType.RequestBody);
IRestResponse responseCreateOrder = client.Execute(request);

Crawl Wikipedia using ASP.NET HttpWebRequest

I am new to Web Crawling, and I am using HttpWebRequest to crawl data from sites.
As of now I was successfully able to crawl and get data from my wordpress site. This data was a simple user profile data. (like name, email, AIM id etc...)
Now as an exercise I want to crawl wikipedia, where I will search using the value entered into textbox at my end and then crawl wikipedia with the search value and get the appropriate title(s) from the search.
Now I have the following doubts/difficulties.
Firstly, is this even possible ? I have heard that wiki has robot.txt setup to block this. Though I have heard this only from a friend and hence not sure.
I am using the same procedure I used earlier, but I am not getting the required results.
Thanks !
Update :
After some explanation and help from #svick, I tried the below code, but still not able to get any value (see last line of code, there I am expecting an html markup of the search result page)
string searchUrl = "http://en.wikipedia.org/w/index.php?search=Wikipedia&title=Special%3ASearch";
var postData = new StringBuilder();
postData.Append("search=" + model.Query);
postData.Append("&");
postData.Append("title" + "Special:Search");
byte[] data2 = Crawler.GetEncodedData(postData.ToString());
var webRequest = (HttpWebRequest)WebRequest.Create(searchUrl);
webRequest.Method = "POST";
webRequest.UserAgent = "Crawling HW (http://yassershaikh.com/contact-me/)";
webRequest.AllowAutoRedirect = false;
ServicePointManager.Expect100Continue = false;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(data2, 0, data2.Length);
requestStream.Close();
var responseCsv = (HttpWebResponse)webRequest.GetResponse();
Stream response = responseCsv.GetResponseStream();
// Todo Parsing
var streamReader = new StreamReader(response);
string val = streamReader.ReadToEnd();
// val is empty !! <-- this is my problem !
and here is my GetEncodedData method defination.
public static byte[] GetEncodedData(string postData)
{
var encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(postData);
return data;
}
Pls help me on this.
You probably don't need to use HttpWebRequest. Using WebClient (or HttpClient if you're on .Net 4.5) will be much easier for you.
robots.txt doesn't actually block anything. If something doesn't support it (and .Net doesn't support it), it can access anything.
Wikipedia does block requests that don't have their User-Agent header set. And you should use an informative User-Agent string with your contact information.
A better way to access Wikipedia is to use its API, rather than scraping. This way, you will get an answer that's specifically meant to be read by a custom applications, formatted as XML or JSON. There are also dumps containing all information from Wikipedia available for download.
EDIT: The problem with your newly posted code is that your query returns a 302 Moved Temporarily response to the searched article, if it exists. Either remove the line that forbids AllowAutoRedirect, or add &fulltext=Search to your query, which will mean you won't get redirected.