How to programmatically get the version of an app on Huawei AppGallery? - android

I know how it can be done for Google Play Store (answer here), but i didn't manage to find a way for AppGallery.
Thank you!
UPDATE #1
Using the answer below i partially solve this with this steps:
Make an API Client with Administrator role, it also works with App Administrator and Operations. (documentaion here: API Client)
Get the access token. (documentaion here: Obtaining a Token)
Get app info. (documentaion here: Querying App Information)
The response from the Querying App Information, have a lot of informations about the app including "versionNumber", but for me it doesn't provide the "versionNumber" (the single info i needed), because this parameter is optional. And now i am stuck again, because i don't understand what i need to change in order to receive this one.
If anyone knows how I can solve this, thank you very much for your help.
UPDATE #2
#shirley's comment was right.
The issue has been fixed in their latest release, and it has been released this month.

You can call the Querying App Information API (GET mode) to query the app details:
public static void getAppInfo(String domain, String clientId, String token, String appId, String lang) {
HttpGet get = new HttpGet(domain + "/publish/v2/app-info?appid=" + appId + "&lang=" + lang);
get.setHeader("Authorization", "Bearer " + token);
get.setHeader("client_id", clientId);
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpClient.execute(get);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
BufferedReader br =
new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), Consts.UTF_8));
String result = br.readLine();
// Object returned by the app information query API, which can be received using the AppInfo object. For details, please refer to the API reference.
JSONObject object = JSON.parseObject(result);
System.out.println(object.get("ret"));
}
} catch (Exception e) {
}
}
They are mentioned here: Completing App Information, Querying App Information.

Related

How to authenticate the http protocol url in android for azure web services?

I have an url with http://. So, i have to authenticate this with user credentials(username and password). I tried so many ways but i am not able to get the data. Everytime i got 401 error(unauthorized). How to access that http:// url with authentication. Please help me.
My code is as follows
DefaultHttpClient Client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"My-URL");
httpGet.addHeader(
"Authorization",
"Basic "
+ Base64.encodeToString(unp.getBytes(),
Base64.NO_CLOSE));
httpGet.setHeader("Content-Type", "application/json");HttpResponse response = Client.execute(httpGet);
System.out.println("response = " + response);
BufferedReader breader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
StringBuilder responseString = new StringBuilder();
String line = "";
while ((line = breader.readLine()) != null) {
responseString.append(line);
}
breader.close();
result = responseString.toString();
System.out.println("responseStr = " + result);
} catch (IOException e) {
e.printStackTrace();
}
i got 400 error(invalid host name). Could you please help me in this.
Azure Mobile Services does not support Basic authentication (unless you actually do the decode yourself). However, the error message suggests you are not getting that far. Your URI should look something like https://your-website.azure-mobile.net.
Potential Solutions (either-or):
Switch to a supported authentication scheme - these are listed in the article that Chris Anderson referenced.
Write a website for Azure App Service Web Apps that does support basic authentication. I'd recommend ExpressJS + Passport for this - here is a tutorial: http://blog.modulus.io/nodejs-and-express-basic-authentication
You don't seem to be using the Azure Mobile Services SDK, so this should cause no problems. However, Basic authentication is relatively insecure, so I recommend looking at the alternate authentication mechanism that Chris suggests.

Retrieving image link after upload fails

I am trying to create a image upload module Using Imgur API
I have just got Client ID and Client Secret after registration. When it comes to the implementation and testing, it fails and gives the following response in the logcat
The Logcat response
{"data":{"error":"We're really sorry, but
anonymous uploading in your country has
been disabled. Please <a href=\"\/register\">register
for an account<\/a> and try uploading again.","request":"\/3\/upload.json","method":"POST"}
,"success":false,"status":400}
The below is my code
public String uploadToImgur(File uploadFile) {
DefaultHttpClient defaulthttpclient;
HttpPost httppost;
MultipartEntity multipartentity;
String path = uploadFile.getAbsolutePath().toString();
String s;
defaulthttpclient = new DefaultHttpClient();
String targetURL = "https://api.imgur.com/3/upload.json";
String apikey = "client_secret";
httppost = new HttpPost(targetURL);
httppost.setHeader("User-Agent", USER_AGENT);
httppost.addHeader("Authorization", "Client-ID {client)_id}");
multipartentity = new MultipartEntity();
s = path.substring(1 + path.lastIndexOf("."));
if (s.lastIndexOf("jpg") >= 0)
{
s = "jpeg";
}
try
{
multipartentity.addPart("image", new FileBody(new File(path), (new StringBuilder("image/")).append(s).toString()));
multipartentity.addPart("key", new StringBody(apikey));
httppost.setEntity(multipartentity);
String s1 = EntityUtils.toString(defaulthttpclient.execute(httppost).getEntity());
Log.d("outpur" , s1);
if (s1.lastIndexOf("<original>") >= 0 && s1.indexOf("</original>") >= 0)
{
return (new StringBuilder("[img]")).append(s1.substring(10 + s1.lastIndexOf("<original>"), s1.indexOf("</original>"))).append("[/img]").toString();
}
}
catch (Exception exception)
{
return "ERRor";
}
return "Error";
}
Would you please tell me what is the better way to enhance the upload module ?
Registration and sending client id is not good enough for non anonymous uploads. The documentation tells you to use oAuth and get a token that needs to be passed for such requests.
Authentication
The API requires each client to use OAuth 2 authentication. This means you'll have to register your application, and generate an access_code if you'd like to log in as a user.
For public read-only and anonymous resources, such as getting image info, looking up user comments, etc. all you need to do is send an authorization header with your client_id in your requests. This also works if you'd like to upload images anonymously (without the image being tied to an account), or if you'd like to create an anonymous album. This lets us know which application is accessing the API.
Authorization: Client-ID YOUR_CLIENT_ID
For accessing a user's account, please visit the OAuth2 section of the docs

Google Books API for Android - Access Not Configured

I am using google books API KEY for android to load book data via my android application. But I am getting error listed below.
However,
- The query works if I delete certificates from my API CONSOLE (e.g. make API KEY acceptable for all Applications). Though my {SHA1};{package name} information that I put is correct.
- This works if I use API KEY for browser instead.
Hence, what I can understand, I can't send KEY as a part of url in httpclient method. May be I need to send via header or something. But I can't find how.
Anybody can help please?
CODE:
String link = "https://www.googleapis.com/books/v1/volumes?key=MY_KEY&q="+query+"&projection=full&langRestrict=en&maxResults=1";
HttpGet get = new HttpGet(link);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpclient.execute(get);
HttpEntity entity = response.getEntity();
Query:
https://www.googleapis.com/books/v1/volumes?key=MY_API_KEY&q=intitle:'The+Old+Man+And+The+Sea'+inauthor:'Ernest+Hemingway'&projection=full&langRestrict=en&maxResults=1
Result:
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured"
}
],
"code": 403,
"message": "Access Not Configured"
}
}
For whom it may concern ... I send my API key in header, and it is now working.. I am not sure whether this is the proper way to it though ...
String link = "https://www.googleapis.com/books/v1/volumes?q="+params;
InputStream is = null;
try
{
int timeoutConnection = 10000;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(timeoutConnection);
con.setReadTimeout(timeoutConnection);
con.setRequestProperty("key", "API_KEY");
if(con.getResponseCode() != HttpURLConnection.HTTP_OK){
publishProgress("Error conneting.");
}
is=con.getInputStream();
}
Supplying the key in the header is the same as not supplying a key at all. Check your developer api console and you will see no successful queries with that api key. So in short the API key in header does not solve the problem. If you don't want to play by google's rules just do the query without the key at all.
You can achieve the same result of the accepted answer using HttpGet:
String API_KEY = "..."; // Google Books API Public key
String ISBN = "...";
String bookSearchString = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + ISBN;
HttpClient bookClient = new DefaultHttpClient();
try
{
//get the data
HttpGet bookGet = new HttpGet(bookSearchURL);
bookGet.addHeader("key", API_KEY);
HttpResponse bookResponse = bookClient.execute(bookGet);
StatusLine bookSearchStatus = bookResponse.getStatusLine();
if (bookSearchStatus.getStatusCode() == 200)
{
//we have a result
HttpEntity bookEntity = bookResponse.getEntity();
...
}
} catch (Exception e)
{
e.printStackTrace();
}
Note that using Google API key without restrictions is insecure way to do!
Obviously if you’re being charged for access to the API data then you don’t want someone to decompile your APK, find your API key, and then start using it in their own apps.
How to hide your API Key in Android?
But It's not enough. You can store your API key somewhere, so someone can find it too.
To secure Google cloud API key for your android app, you must restrict it to use from your app only. See here for more.
After restrict key, you must include your android app package name and SHA-1 certificate fingerprint in the header of each request you are sending to Google. How to do?
That's all you need ! :D

Right credentials in requestBody for Android Google Play Oauth2 gtalk authToken

Running the code below I get "error" : "unauthorized_client". Need help pinpoint what I have done wrong.
I Want to use this in an Android app to enable Google Talk (xmpp is there already XABBER fork)
Reading much about how to do this and now come the Google Api Console setup.
I have chosen
- Client ID for installed applications
- Installed application type = Other
- Enabled only the Google Play Android Developer API (green switch)
I get the authentication token from oauth2:https://www.googleapis.com/auth/googletalk. (user approval screen)
What bugs me I dont enter the SHA1 fingerprint or package name for "Other" so maybe that's the problem
code:
HttpClient client1 = new DefaultHttpClient();
HttpPost request1 = new HttpPost("https://accounts.google.com/o/oauth2/token" );
request1.setHeader("Content-type", "application/x-www-form-urlencoded");
//Please make this custom with you're credentials
String requestBody1 =
"code="+authToken+
"&client_id=749825062016ia.apps.googleusercontent.com"+
"&client_secret=jQ1nUrAYUIBUf6hN5pwPE" +
"&redirect_uri=urn:ietf:wg:oauth:2.0:oob" +
"&grant_type=authorization_code";
try {
request1.setEntity(new StringEntity(requestBody1));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/* Checking response */
try {
HttpResponse response = client1.execute(request1);
String results = "ERROR";
results = EntityUtils.toString(response.getEntity());
LogManager.i("STACK", "Response::" + results);
} catch (IOException e) {
e.printStackTrace();
}
I think you should have registered your application with type 'Android'. Then you will be asked to provide information (such as package name and certificate) that will allow the Android platform to recognize your application.

Unable to get expected response for Facebook photos from an album

I am new to Facebook API. Trying the FQL Query from the Graph API for the first time using this link.
I am trying to get photos from the album with the album id. When I request using Facebook object with https://graph.facebook.com/10150146071791729/photos&access_token=ACCESS_TOKEN URL, I am getting the following response (before parsing to JSON object). {"id":"https://graph.facebook.com/10150146071791729/photos","shares":2}. And I confirmed it by printing the length of the JSON object after parsing, which is 2. When I copy and paste the same URL in the web browser, I am getting the expected response (the response in FQL Query I got). Here is my code.
public void onComplete(Bundle values) {
String token = facebook.getAccessToken();
System.out.println("Token: " + token);
try {
String response = facebook.request("https://graph.facebook.com/10150146071791729/photos&access_token=ACCESS_TOKEN");
System.out.println("response :"+response);
JSONObject obj = Util.parseJson(response);
System.out.println("obj length : " + obj.length());
Iterator iterator = obj.keys();
while(iterator.hasNext()){
String s = (String)iterator.next();
System.out.println(""+s+" : "+obj.getString(s));
}
} catch (Throwable e) {
e.printStackTrace();
}
}
Note: I got access token from the FQL Query which is used in the URL. And I did not wrote any session (login/logout) logic as it is a test project.
Your request is wrong. It should be
"https://graph.facebook.com/10150146071791729/photos?access_token=ACCESS_TOKEN"
Replace the '&' after the photos with a '?'.
Two more things, you're making a Graph API query, not an FQL one.
Second, NEVER post your access tokens publicly. If I wanted to, I can now use your access token to edit your facebook information.
EDIT: When you use the Android Facebook SDK, you do not need to use the full graph path. Instead, use
facebook.request("10150146071791729/photos")
You do not need to add the access token as the Facebook object already has it. Hope this helps.
Because not much code has been provided except for the most relevant one, let me give you a couple of ways you can access Photos from an Album
FIRST METHOD (IF your wish to use the complete URL to make the request)
String URL = "https://graph.facebook.com/" + YOUR_ALBUM_ID
+ "/photos&access_token="
+ Utility.mFacebook.getAccessToken() + "?limit=10";
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String queryPhotos = EntityUtils.toString(rp.getEntity());
Log.e("PHOTOS RESULT", queryPhotos);
}
} catch (Exception e) {
e.printStackTrace();
}
SECOND METHOD (Without using the complete URL as #Vinay Shenoy mentioned earlier)
try {
Bundle paramUserInfo = new Bundle();
paramUserInfo.putString(Facebook.TOKEN, Utility.mFacebook.getAccessToken());
String resultPhotos = Utility.mFacebook.request("YOUR_ALBUM_ID/photos", paramUserInfo, "GET");
Log.e("PHOTOS", resultPhotos);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
On a personal note, I follow the first method almost entirely through my application. It lets me using the Paging for endless ListViews
That being said, when I need some quick data in between somewhere, I do rely on the second method. Both of them work and I hope either (or both) of them helps you.

Categories

Resources