Parse Twitter Timeline json Windows Phone - json

I'm trying to parse Twitter timeline, but I have an error: The remote server returned an error: NotFound.
Here is code:
private void GetUserTimeLine(string userName)
{
WebClient wcTwitterTimeline = new WebClient();
wcTwitterTimeline.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wcTwitterTimeline_DownloadStringCompleted);
wcTwitterTimeline.DownloadStringAsync(new System.Uri("http://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" + userName));
}
void wcTwitterTimeline_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
List<RootObject> tweets = JsonConvert.DeserializeObject<List<RootObject>>(e.Result);
this.listboxMyTimeline.ItemsSource = tweets;
Dispatcher.BeginInvoke(() =>
{
listboxMyTimeline.Visibility = Visibility.Visible;
txtBoxNewTweet.Visibility = Visibility.Visible;
btnPostTweet.Visibility = Visibility.Visible;
});
}
Error begins here:
List<RootObject> tweets = JsonConvert.DeserializeObject<List<RootObject>>(e.Result);

The 404 Not Found might be because you're URL scheme is http and should be https. After you resolve this, your next error might be 401 Unauthorized because Twitter API v1.1 requires OAuth authentication. You might want to check out the Twitter API FAQ and referenced docs for more details.

Related

Error trying to connect to an mvc server on ms-azure from a windows phone 8 app using webapi

I'm a little bit new to all of these technologies so I'll try to be as clear as I can.
I'm writing a windows phone app that sends data in string format to a server:
public class sendDataControl
{
private string response = "";
public void sendToServer(string FullSTR)
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://pricequeryserver.azurewebsites.net/api/ReceiptDataService/?incomingdata=");
webClient.UploadStringAsync(uri,FullSTR);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
}
catch (Exception ex)
...
...
}
}
void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
{
responseXml=e.Error.Message;
MessageBox.Show(responseXml);
return;
}
else
{
responseXml = e.Result;
}
}
}
The server is an MVC4, basic, with api controller I added, that needs to get the data sent from the mobile.
As a test I'm just getting back a string that I send:
public class ReceiptDataServiceController : ApiController
{
private ReceiptContext db = new ReceiptContext();
...
...
public string GetDataFromMobile(string IncomingData)
{
return IncomingData;
}
}
While running the application I get an error via responseXml:
"The remote server returned an error: NotFound".
The server returns the right answer from all kinds of browsers, while on IIS and on the azure but not from the mobile emulator.
Any suggestions?
If you take a look at the documentation for UploadStringAsync overload you are using, you will notice that it sends data using POST method. While in your controller you have only implemented GET. And for your
You have to use other overload of UploadStringAsync, which lets you specify the HTTP VERB to use. And you must specify GET. Your client code should be converted to:
webClient.UploadStringAsync(uri,"GET", FullSTR);
And the best solution for simple GET operations like your is to actually use DownloadStringAsync:
var fullUri = new Uri("http://pricequeryserver.azurewebsites.net/api/ReceiptDataService/?incomingdata=" + FullStr);
webClient.DownloadStringAsync(fullUri);
Anyway, your question has nothing to do with Windows Azure, thus the removed tag.

How to post messages to yammer private network

I want to post messages to yammer in different network. For this I have wrote the below code ,
it's giving the server not found exception.
rawtoken = Security.GetRawToken();
//TODO
//get list of Yammer tokens for this user
WebClient wc = new System.Net.WebClient();
wc.DownloadStringCompleted += wc_DownloadStringCompleted;
wc.DownloadStringAsync(new Uri("https://www.yammer.com/api/v1/oauth/tokens.json?access_token=" + rawtoken));
void wc_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
string tokens = e.Result;
MessageBox.Show(tokens);
List<Response> myDeserializedObjList = (List<Response>)Newtonsoft.Json.JsonConvert.DeserializeObject(tokens,typeof(List<Response>));
List<Response> response = myDeserializedObjList.Where(item => item.network_id == "992371").ToList();
accessToken = response[0].token;
WebClient wc = new System.Net.WebClient();
Uri uri = new Uri("https://www.yammer.com/api/v1/messages.json?access_token=" + accessToken);
student ns = new student();
// wc.Headers["Authorization"] = "Bearer " + accessToken; //use discoEN token here
String data = "group-id=" + ns.group_id + "&body=" + ns.body;
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
wc.UploadStringTaskAsync(uri, data);
}
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
You should use the SDK for Windows Mobile rather than rolling your own code. It is available from the Yammer Developer site. Your code also passes the token on a URL parameter. This is no longer supported and you need to pass it on the authentication header.
A ServerNotFoundException highlights a connectivity problem. Perhaps you are not connected to the network, cannot route connections, or cannot resolve www.yammer.com via DNS.

Getting response status code 0 in SmartGWT webservice call using json

I have developed application using SmartGWT. Now I need to call webservice using json to another application which is deployed in another server for submitting username and password. When I make a request with url and POST method, getting the response status code as 0 and response text as blank.
Here is my code,
public void sendRequest() throws Exception {
// Get login json data to be sent to server.
String strData = createLoginReqPacket();
String url = "some url";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/json");
builder.setHeader("Content-Length", strData.length() + "");
Request response = builder.sendRequest(strData, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
int statusCode = response.getStatusCode();
System.out.println("Response code ----"+response.getStatusCode()+"");
if (statusCode == Response.SC_OK) {
String responseBody = response.getText();
System.out.println("Respose :" + responseBody);
// do something with the response
} else {
GWT.log("Response error at server side ----",null);
// do in case of server error
}
}// end of method.
#Override
public void onError(Request request, Throwable exception) {
GWT.log("**** Error in service call ******",null);
}// end of method.
});
builder.send();
}// end of send request.
Please anybody knows the solution?
as i am new to GWT/SmartGwt i don't no much about it.
#ModeEngage
There is no reason to use GWT class(RequestBuilder), But i don't have any idea to use Data source. Can u give reference or stuffs to do this??
And when i run this in chrome browser i get the following in error console.
XMLHttpRequest cannot load http:// "requested Url" . Origin http:// "localhost:8888" is not allowed by Access-Control-Allow-Origin.
Any solutions???
I believe this is caused by Firewall. I've run some test, and this is the most likely explanation.

Android App: Acquire Access Token for Google Drive API

I am writing an Android (version ICS) app. which uploads data to the Google Drive. The app
uses oauth2 to acquire the access token.
First step: acquire authorization token.
String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/drive";
// Step 1
accountManager.getAuthToken(
account, // Account retrieved using getAccountsByType("com.google")
AUTH_TOKEN_TYPE, // Auth Token Type
options, // Authenticator-specific options
this, // Your activity
new OnTokenAcquired(), // Callback called when a token is successfully acquired
new Handler(new OnAuthTokenError())); // Callback called if an error occurs
}
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
// Get the result of the operation from the AccountManagerFuture.
Bundle bundle;
try {
bundle = result.getResult();
authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
Log.d(TAG,"authToken:" + authToken);
exchangeToken access = (exchangeToken) new exchangeToken().execute();
} catch (OperationCanceledException e) {
e.printStackTrace();
} catch (AuthenticatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Success. An authorization token is acquired.
Step 2: Exchange authorization token for Access Token.
private class exchangeToken extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
HttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new GsonFactory();
String CLIENT_ID = "999999999999.apps.googleusercontent.com";
String CLIENT_SECRET = "axXXXXXXXXXXXXXXX7";
try { // Step 2: Exchange for an access and refresh token
GoogleTokenResponse authResponse = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, authToken, CALLBACK_URL).execute();
accessToken = authResponse.getAccessToken();
Log.d("Get Access","Token:" + accessToken);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Fail. The LogCat shows the following:
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error":"unauthorized_client"
}
I have been able to access "Google Drive" on my Android tablet using the "Drive" app. so
my email account is valid. May be the AUTH_TOKEN_TYPE is incorrect, but the Google Drive
SDK is not clear what it must be. What am I missing?
You do not need to do the second step of exchanging the token. Android grants you an access token directly, it does not grant you an auth code which you would have to exchange for tokens.
This page on the Android documentation explains everything really well.
You know that for using the Drive API your users have to install your app on the Chrome(!) Webstore?
Normally Documents List API is the better choice from Android.

How do I read the basic authorization in a ASP.Net MVC4 api GET request

I have a phone app that trys to GET data from my web api using RestSharp
private void ButtonTestTap(object sender, EventArgs e)
{
var client = new RestClient
{
CookieContainer = new CookieContainer(),
BaseUrl = "http://localhost:21688/api/game",
Authenticator = new HttpBasicAuthenticator("muhcow", "123456")
};
RestRequest request = new RestRequest(Method.GET);
request.AddParameter("id", 5);
//request.AddBody(5);
client.GetAsync<LoginResult>(request, (response, ds) =>
{
System.Diagnostics.Debug.WriteLine(response.StatusDescription);
System.Diagnostics.Debug.WriteLine(response.Data);
System.Diagnostics.Debug.WriteLine(response.Content);
});
}
And then want to read the Authenticator = new HttpBasicAuthenticator("muhcow", "123456") when my api server recieves this GET request so I can verify the user, but I am not sure how to read the data.
I have this
public class GameController : ApiController
{
// GET /api/game/5
public string Get(int id)
{
var sdf2 = ControllerContext.Request.Headers.Authorization.Parameter;
//return LoginManager.VerifyLogin(loginData);
return "Some data";
}
But sdf2 just has a wierd value "bXVoY293OjEyMzQ1Ng=="
That header is base64-encoded. Apply Convert.FromBase64String() to it and you'll see the contents.
Authorization.Parameter is base64 encoded. You can look at an example of how to decode it here http://arcanecode.com/2007/03/21/encoding-strings-to-base64-in-c/
System.Text.Encoding.UTF8.GetString (Convert.FromBase64String (this.ControllerContext
.Request .Headers.Authorization.Parameter ))
the result is
"muhcow", "123456"