Authentication error when connect to Google Tasks API by HttpClient - android

I am trying to connect to the Google Tasks by using HttpClient but always get "Unauthorised HttpResponseException".
Here is my code inside the "run" method of the AccountManagerCallback
#Override
public void run(AccountManagerFuture<Bundle> result) {
// Get the result of the operation from the AccountManagerFuture.
Bundle bundle;
try {
bundle = result.getResult();
token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
Log.i("#######", token); // token does have value
String url = "https://www.googleapis.com/tasks/v1/users/#me/lists?key=" + your_api_key;
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("client_id", your_client_id);
getRequest.addHeader("client_secret", your_client_secret);
getRequest.addHeader("Authorization", "OAuth " + token);
HttpClient httpclient = new DefaultHttpClient();
String responseBody = httpclient.execute(getRequest, new BasicResponseHandler()); // exception raised here
Log.i("###", responseBody); // cannot get the response here
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am using Google APIs Level 10 emulator which does have access to the internet and I did add an google account into it.
Appreciate for any helps or suggestions to make my code work. Thanks.

Related

Google places adding event invalid request

I'm trying to add an event in google places and the JSON returned has an invalid request in status and this endpoint has been removed in error_message. This morning it has worked correctly but now it doesn't work anymore.
I tried to use HTTP in the request to see if it returns the request denied but this doesn't do it, it always returns invalid request.
Here is my code:
private final String EVENT_URL =
"https://maps.googleapis.com/maps/api/place/event/add/json?";
private JSONObject uploadEvent() {
JSONObject jsonobj = new JSONObject();
StringEntity sEntity = null;
try {
jsonobj.put("duration", duration);
jsonobj.put("reference", reference);
jsonobj.put("summary", description);
if(url.length() > 0){
jsonobj.put("url", url);
}
sEntity = new StringEntity(jsonobj.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(getUrlEvent());
httppostreq.setEntity(sEntity);
String responseText;
JSONObject JSON = null;
try {
HttpResponse httpresponse = httpclient.execute(httppostreq);
responseText = EntityUtils.toString(httpresponse.getEntity());
JSON = new JSONObject(responseText);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
private String getUrlEvent(){
//genero la solicitud como la debajo descrita
StringBuilder urlString = new StringBuilder(EVENT_URL);
urlString.append("&sensor=false&key=" + API_KEY);
return urlString.toString();
}
Can anyone helps me please?
Try
sEntity.setContentEncoding("UTF-8");
sEntity.setContentType("application/json");
httppostreq.addHeader("Content-Type", "application/json");
To quote the documentation:
Note: Events and place bumps were deprecated on September 3, 2014. The deprecation period has now ended. As of February 10th, 2015, the
API no longer accepts event or bump actions, and no longer returns
events in Place Search or Place Details responses.

Android FTPClient connection to local host

how to connect to local host from android ftp client with emulator? What ip and port number should used in method "connect(host,port)"? When I tried with 10.0.2.2,127.0.0.1 with port number 21 the connection is refused. I am using Ubuntu with eclipse.
please help...
you should use Asynctask like this code :
#Override
protected ArrayList doInBackground(String... params) {
// TODO Auto-generated method stub
//activity is defined as a global variable in your AsyncTask
try {
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet(params[0]);
HttpResponse hr = hc.execute(hg);
HttpEntity he = hr.getEntity();
data = EntityUtils.toString(he);
Log.i("data", data);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and then when you use it like this :
new asy().execute("http:// put your ip address here ");

Posting image using tumblr

{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}
Tumblr gives above result while posting image.
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = null;
String result = null;
HttpPost hpost = new HttpPost("http://api.tumblr.com/v2/blog/" + username
+".tumblr.com/post");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("type", "photo"));
nameValuePairs.add(new BasicNameValuePair("caption", "hello"));
nameValuePairs.add(new BasicNameValuePair("source", "url_of_the_image"));
String debug = "";
try {
hpost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
consumer.sign(hpost);
resp = client.execute(hpost);
result = EntityUtils.toString(resp.getEntity());
Log.v("result >>", result);
} catch (UnsupportedEncodingException e) {
debug += e.toString();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I need to post the image in tumblr. Give me some solutions.
Have you considered using a third-party library? The Temboo SDK (free account required) includes methods to create Tumblr photo posts either by passing a photo URL or the Base64 encoded content of the photo. Take a look at:
https://www.temboo.com/library/Library/Tumblr/Post/CreatePhotoPostWithURL/ https://www.temboo.com/library/Library/Tumblr/Post/CreatePhotoPostWithImageFile/
Full disclosure -- I work at Temboo.

In background check the Play Store to determine if an app is available to download on the device

I know I can link to the Play Store with the URL:
market://details?id=com.example.appname
What I would love to do is 'ping' this URL in the background, and determine if the app is actually available, then, I can modify my UI as appropriate.
Let's assume that, if app is unavailable, the page under http://play.google.com/store/apps/details?id=<package_name> contains, for example, word error-section. If app is available, it does not contain this word.
Make HTTP GET to that URL and search for error-section.
No error-section - your app is available.
Otherwise, it's unavailable.
Like this:
final HttpClient client = new DefaultHttpClient();
final String getURL = "http://play.google.com/store/apps/details?id=<package_name>";
final HttpGet get = new HttpGet(getURL);
final HttpResponse responseGet = client.execute(get);
final HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null)
{
final String response = EntityUtils.toString(resEntityGet);
if (response.indexOf("error-section") == -1)
{
// available
}
else
{
// unavailable
}
}
private class URLTest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
try {
HttpClient httpclient = new DefaultHttpClient();
String strurl = "https://play.google.com/store/apps/details?id=com.rovio.angrybirdsstarwars.ads.iap";
// String strurl =
// "https://play.google.com/store/apps/details?id=com.rovio.angrybirdsstarwars.ads.iaptest";
// //fake packagename append with "test"
HttpGet httpget = new HttpGet(strurl);
HttpResponse httpresp = httpclient.execute(httpget);
if (httpresp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Log.e("Found", "YES");
} else if (httpresp.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
Log.e("Found", "NO");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
Log.e("", "");
}
return null;
}
}
i tried with correct & fake packages and its giving bad request responze if the app not available & positive(success 200 code) if app is there..so plz check it once it might help u.
android 2.2 & app min req 2.3

Android - HttpClient execute has a mind of its own - 1 second or 200 seconds

I'm trying to use HttpClient to connect to a php page that logs in and passes back a sessionid and then goes to a new page, using that sessionid and obtains a mySQL datafield associated with that sessionid.
On the first request, HttpClient can take 1.5 seconds, 6 seconds, or 2 minutes. If the first request was slow, subsequence requests seem to be faster, and visaversa.
The HttpClient request occurs when a Button view is clicked
Here's my code:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
name = (TextView)findViewById(R.id.name);
user = (EditText) findViewById(R.id.user);
pass = (EditText) findViewById(R.id.pass);
submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(this);
HttpParams params1 = new BasicHttpParams();
params1.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
client = new DefaultHttpClient(params1);
httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Create local HTTP context
}
public void onClick(View v) {
if (v.getId() == R.id.button1) {
//submit.setClickable(false);
String username = user.getText().toString();
String password = pass.getText().toString();
String targetURL = "<<<<LOGIN PHP URL>>>>";
post = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("params","params added");
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d("entity added","entityadded");
Log.d("preex","PRE EXECUTION");
localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//submit.setText("Logging In...");
new Thread(new Runnable(){
public void run(){
try {
Log.d("pre","pre execute");
response = client.execute(post,localContext);
Log.d("post","post execute");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("response: ",convertStreamToString(input));
getFullName(localContext);
}
}
}).start();}
}
private void getFullName(final HttpContext context){
Log.d("called","called");
String targetURL = "<<<<SESSION CHECKER PHP URL>>>>";
//client1 = new DefaultHttpClient();
post1 = new HttpPost(targetURL);
Log.d("","about to call runable....");
// submit.setText("Obtaining Full Name...");
try {
Log.d("pre","CALLING!");
response = client.execute(post1,context);
Log.d("post","called..");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
//submit.setText("Full Name Obtained!...");
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.d("response: ",convertStreamToString(input));
outputResponse(input);
}
}
private void outputResponse(final InputStream in) {
name.post(new Runnable(){
public void run(){
String fullname=convertStreamToString(in);
name.setText("Full Name is: "+fullname);
}
});
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Before I set Http version 1.1 it took double the time, but for my application, the speed cannot be unreliable. This is all on a pretty fast WiFi connections -- can you image Edge or 3G speeds??
So what can I optimize?
Thanks everyone:)
EDIT: I did a new test with: http://www.posttestserver.com/ and it happened pretty fast. The urls I'm using currently aren't my final server urls, they are for a different site on a different server -- shared hosting, so could it be that contacting my shared hosting site is just slow and will be compared to my .net server?
Thanks again !

Categories

Resources