I'm experimenting with the soundcloud API and try to extract all playlist titles from my JSON object, to make a list with references. Actually I don't have many experience with JSON and therefore I just can't manage to call any variable form the decoded JSON array...
http://api.soundcloud.com/users/55607614/playlists.json?client_id=YOUR_CLIENT_ID
I already did take a look on the structure via http://jsonviewer.stack.hu/ but it didn't really help me out...
$json = json_decode(file_get_contents("http://api.soundcloud.com/users/55607614/playlists.json?client_id=YOUR_CLIENT_ID"));
echo $json[??][??]...;
Any ideas? Thanks!
private SCPlaylistObject playListObject, plTestObject;
public string TrackList;
private List<SCTrackObjects> TListTest;
/// <summary>
/// Deserializes JSON data into object from string
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString"></param>
/// <returns>json object</returns>
public static T Deserialize<T>(string jsonString)
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
MemoryStream MemStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
T result = (T)deserializer.ReadObject(MemStream);
return result;
}
public async Task<string> GetUserTracks() // Async Call to get user id
{
try
{
responseText = await GetjsonStream();
SCUserID = userObject.id;
TrackList = await GetTracks();
TList = Deserialize<List<SCTrackObjects>>(TrackList);
return TrackList;
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.Message);
return ex.Message;
}
public async Task<string> GetTracks() //Function to read from given url
{
HttpClient client = new HttpClient();
string url = SCLink + SCAPIUsers + SCUserID + "/tracks?client_id=" + soundcloudAPI;
HttpResponseMessage response = await client.GetAsync(url);
HttpResponseMessage v = new HttpResponseMessage();
return await response.Content.ReadAsStringAsync();
}
}
public async Task<string> GetjsonStream() //Function to read from given url
{
HttpClient client = new HttpClient();
string url = SCLink + SCAPIUsers + SCNameField + ".json?client_id=" + soundcloudAPI;
HttpResponseMessage response = await client.GetAsync(url);
HttpResponseMessage v = new HttpResponseMessage();
return await response.Content.ReadAsStringAsync();
}
Related
I want to get JSON data from Site
Nothing shows up about it and Xamarin and I tried these 3 from youtube and it didn't work for me
public void ValidateNumber()
{
string URL = "http://android-householdinventory-api.epizy.com/ValidateNumber.php?";
WebClient client = new WebClient();
Uri uri = new Uri(URL + "number=10");
client.DownloadDataAsync(uri);
client.DownloadDataCompleted += Client_DownloadDataCompleted;
}
private void Client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
//throw new NotImplementedException();
string json = Encoding.UTF8.GetString(e.Result);
System.Console.WriteLine(json);
}
public async void Validationv2()
{
using (var client = new HttpClient())
{
var uri = "http://android-householdinventory-api.epizy.com/ValidateNumber.php?number=100";
var Result = await client.GetStringAsync(uri);
System.Console.WriteLine(Result);
}
}
public void Validationv3()
{
WebClient wclient = new WebClient();
string a = wclient.DownloadString("http://android-householdinventory-api.epizy.com/ValidateNumber.php?number=100");
System.Console.WriteLine(a);
}
All Results to this:
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("304feeb55638873348a9f20961a94049");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://android-householdinventory-api.epizy.com/ValidateNumber.php?number=10&i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
How to fix this?
I'm new to c# and Xamarin
Your API server is returning HTML response for this "http://android-householdinventory-api.epizy.com/ValidateNumber.php?number=100" end point that's why it is showing HTML in response. You will have to correct the api response on server side.
try this! working example
private async void btn_Login_Clicked(object sender, EventArgs e)
{
List<LoginDetails> UserDetails = await _services.LoginAsync(string username, string password)
}
public async Task<List<LoginDetails>> LoginAsync(string username, string password)
{
List<LoginDetails> UserList;
using (var client = new HttpClient())
{
LoginDetails Ld = new LoginDetails();
Ld.UserName = username;
Ld.Password = password;
string url = "";
//HttpClient client = new HttpClient();
string jsonData = JsonConvert.SerializeObject(Ld);
StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
UserList = JsonConvert.DeserializeObject<List<LoginDetails>>(result);
//loginDetails = new ObservableCollection<LoginDetails>(UserList);
}
return UserList;
}
I was hosting on InfinityFree and it has aes.js so it may be causing that result.
This helped me in getting the solution
Setting Authorization Header of HttpClient
ByetHost server passing html values "Checking your browser" with JSON String
[I added this before client.GetAsync]
client.DefaultRequestHeaders.Add("Cookie", "__test=<COOKIE_CONTENT>; expires=<COOKIE_EXPIRATION>; path=/");
I would like to work on moving the json data from libgdx to my web server, but I am not sure how to do it. The method below was created by referring to libgdx's documentation.
private void httpPostJson(){
final Json json = new Json();
final String requestJson = json.toJson(requestObject);
Net.HttpRequest request = new Net.HttpRequest("POST");
final String url = "http://localhost:8080/data";
request.setUrl(url);
request.setContent(requestJson);
request.setHeader("Content-Type", "application/json");
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String responseJson = httpResponse.getResultAsString();
Gson gson = new Gson();
data = gson.fromJson(responseJson, Person.class);
//'Person' is just sample class. data is class Person's object.
data.StoreData("",1);//successed to receive json data from web server.
//StoreData is just getter method.
}
#Override
public void failed(Throwable t) {
Gdx.app.log("failed!");
}
#Override
public void cancelled() {
Gdx.app.log("cancelled!");
}
});
}
It is possible to receive data transmitted from a web server.
But, this method can't send data to web server.
Can you tell me how to move data from libgdx project to web server?
This is the data transmitted to the web server:
final String requestJson = json.toJson(requestObject);
We are using the following Code (as you have more control over the request as opposed to using gdx.net), works like a charm, just don't execute on the main thread - body is your JSON as String
URL url = new URL(<your url>);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type",
"application/json; charset=utf-8");
if (body != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(body);
writer.close();
os.close();
}
conn.connect();
String s = stringFromStream(conn.getInputStream(), 4096);
Method stringFromStream:
public static String stringFromStream(final InputStream is,
final int bufferSize) {
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
} finally {
in.close();
}
} catch (Exception ex) {
}
return out.toString();
}
I am trying to POST some JSON data to a remote server and read JSON response back from the remote server. My code is jumping in to the catch exception block with the error ex = {"The remote server returned an error: (500) Internal Server Error."} when it gets to this line near the bottom:
var httpResponse = (HttpWebResponse)request.GetResponse();
I have read a few posts on this forum and tried the code other suggest but I don't understand/can't get it to work.
Please can you help me understand what I am doing wrong? You can see my previous attempt which is commented out near the bottom of the code block.
using System;
using System.Text;
using System.Net;
// include
using System.IO;
using System.Web.UI.WebControls;
using HobbsDPDJSONLibrary;
using System.Web;
using Newtonsoft.Json;
namespace DPDAPILibrary
{
public class DPD_API
{
#region public class variables
private static string dpdapiun = "xxx";
private static string dpdapipw = "xxx";
private static string dpdAccountNumber = "xxx";
private static string dpdapihost = "api.dpd.co.uk";
private static string dpdapiinserttestshipment = "https://api.dpd.co.uk/shipping/shipment?test=true";
private static string dpdapiinsertshipment = "https://api.dpd.co.uk/shipping/shipment";
#endregion
/// <summary>
/// Send consignment data to the DPD API to create a shipment and return a consignment number (if successful).
/// </summary>
/// <param name="geoClientData"></param>
/// <param name="JSONData"></param>
/// <returns></returns>
public Boolean insertShipment(string geoSession, bool test, out string JSONdata)
{
try
{
// default output values
JSONdata = "";
bool returnValue = false;
#region create new insert shipment object
// a large block of code here that serialises a class into JSON, this bit works so I have omitted it to reduce the code I post on the forum
#endregion
string InsertShipmentData = JsonConvert.SerializeObject(NewShipmentObject);
// convert the 'insert shipment' JSON data to byte array for posting
//byte[] postBytes = Encoding.UTF8.GetBytes(InsertShipmentData);
// set the target uri for the insert shipment request (defaults to test, or switch to live as per input parameter)
Uri targetURI = new Uri(dpdapiinserttestshipment);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(dpdapiinserttestshipment);
if(!test)
{
targetURI = new Uri(dpdapiinsertshipment);
request = (HttpWebRequest)WebRequest.Create(dpdapiinsertshipment);
}
// add headers to the web request for inserting a new shipment
request.Host = dpdapihost;
request.ContentType = "application/json";
request.Accept = "application/json";
request.Method = "POST";
request.Timeout = 30000;
request.KeepAlive = true;
request.AllowAutoRedirect = false;
request.Headers["GEOClient"] = "thirdparty/" + dpdAccountNumber;
request.Headers["GeoSession"] = geoSession;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(InsertShipmentData);
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
//// run the request and read the response header
//using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
//{
// using (var sr = new StreamReader(response.GetResponseStream()))
// {
// JSONdata = Convert.ToString(sr.ReadToEnd());
// }
// // check if OK (status 200) returned
// if (response.StatusCode.ToString() == "OK")
// {
// returnValue = true;
// }
// else
// {
// returnValue = false;
// }
// return returnValue;
//}
return returnValue;
}
catch (Exception ex)
{
JSONdata = Convert.ToString(ex);
return false;
}
}
}
}
In my MVC Controller, I had the following:
public async Task<ActionResult> Get()
{
WebClient client = new WebClient();
var result = new ContentResult
{
Content = await client.DownloadStringTaskAsync(url),
ContentType = "application/json"
};
return result;
}
But now that I am using an MVC Web API, how do I change this to return a string and not a ActionResult via an Ajax request?
I tried the following and it works, but I get a string instead of a json object.
public async Task<HttpResponseMessage> Get()
{
WebClient client = new WebClient();
String result = await client.DownloadStringTaskAsync(url);
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new ObjectContent<object>(result, new JsonMediaTypeFormatter());
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
Any ideas?
Check the below solution to return the string content in response
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(// Your Object
System.Text.Encoding.UTF8, "application/json") };
I am struggling to successfully implement a POST operation within Windows Phone 8.1.
PostMessage method executes without any exceptions being caught.
However, the POST method within MessagesController never gets invoked.
How do I perform a POST for Windows Phone 8.1?
The code is below:
internal async Task PostMessage(string text)
{
Globals.MemberId = 1;
int memberId = 2;
// server to POST to
string url = #"http://localhost:17634/api/messages";
try
{
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
var message = new Message() { FromId = Globals.MemberId, ToId = memberId, Content = text, Timestamp = DateTime.Now };
var json = string.Format("{0}{1}", "action=", JsonConvert.SerializeObject(message));
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
public class MessagesController : ApiController
{
public HttpResponseMessage Post(Message message)
{
throw new NotImplementedException();
}
}
public class Message
{
public int MessageId { get; set; }
public int FromId { get; set; }
public int ToId { get; set; }
public DateTime Timestamp { get; set; }
public string Content { get; set; }
}
The following link resolved my issue.
The updated client is as follows:
using (var client = new System.Net.Http.HttpClient())
{
// New code:
client.BaseAddress = new Uri(Globals.URL_PREFIX);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var message = new Message() { MessageId = 0, FromId = Globals.MemberId, ToId = memberId, Content = text, Timestamp = DateTime.Now };
var json_object = JsonConvert.SerializeObject(message);
var response = await client.PostAsync("api/messages", new StringContent(json_object.ToString(), Encoding.UTF8, "application/json"));
Debug.Assert(response.StatusCode == System.Net.HttpStatusCode.Accepted);
}
This works fine for me. The function accepts an payload of type T. The server accepts a JSON object and returns a JSON response.
public async static Task SendRequestPacket<T>(object payload)
{
Uri theUri = new Uri("the_uri");
//Create an Http client and set the headers we want
HttpClient aClient = new HttpClient();
aClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
aClient.DefaultRequestHeaders.Host = theUri.Host;
//Create a Json Serializer for our type
DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(T));
// use the serializer to write the object to a MemoryStream
MemoryStream ms = new MemoryStream();
jsonSer.WriteObject(ms, payload);
ms.Position = 0;
//use a Stream reader to construct the StringContent (Json)
StreamReader sr = new StreamReader(ms);
StringContent theContent = new StringContent(sr.ReadToEnd(), Encoding.UTF8, "application/json");
//Post the data
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
if (aResponse.IsSuccessStatusCode)
{
string content = await aResponse.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(content);
}
else
{
// show the response status code
}
}
Just dont use HttpWebRequest if you are not forced to in any way.
This example is using HttpClient() and it is good to always have the client created once and not every time you make a request.
So in your class add:
private static HttpClient _client;
public static Uri ServerBaseUri
{
get { return new Uri("http://localhost:17634/api"); }
}
public ClassConstructor()
{
_client = new HttpClient();
}
internal async Task<ResponseType> PostMessage(string text)
{
Globals.MemberId = 1;
int memberId = 2;
try
{
var js = "{ JSON_OBJECT }";
var json = new StringContent(js);
json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await Client.PostAsync(new Uri(ServerBaseUri, "/messages"), json);
var reply = await response.Content.ReadAsStringAsync();
} catch (Exception)
{
return null;
}
}
More on HttpClient.