I have an Android 2.1 application.
I need that that application download file from my storage in my Azure acount.
I can't use the APIs that Azure provide, Because my Android version is to old.
So, I tried to download that file by Rest service call.
I don't know why didn't I succeed to do that
That what I tried to do:
private String _url = "https://fake_azure_acount_name.blob.core.windows.net/";
private final String _thisClassName = "StorageProvider";
private final String _azurAcountName = "fake_azure_acount_name";
public String GetImage(String imagePath)
{
String image = ExecuteGetRequest(imagePath, "Could not succeed get the requested image");
return image;
}
private String ExecuteGetRequest(String getRequest, String errorMassageIfFailes)
{
DefaultHttpClient httpclient = new DefaultHttpClient();
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(new HttpGet(_url + getRequest));
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
return json;
}
catch(Exception ex)
{
Log.e(_thisClassName, errorMassageIfFailes, ex);
return null;
}
finally
{
try
{
httpclient.getConnectionManager().shutdown();
}
catch(Exception ex)
{
Log.e(_thisClassName, "Failed to close http connection", ex);
}
}
}
What is the right way to do that?
Since you are working directly with the REST API, I would strongly recommend reading the corresponding API documentation: Get Blob. It does not look like you are doing Shared Key authentication, so you have two options:
Your container needs to allow anonymous access.
You need to use a Shared Access Signature.
Please see Authentication for the Azure Storage Services and Delegating Access with a Shared Access Signature for more information on authentication.
Related
I'm looking forward to implement an app which connects to Spotify. To use Spotify services, I need a token, which I can get with the Spotify SDK, however this token is intended for quick expiring not for long term use. In the web API I can make calls from within my server to get new access tokens via refresh_token. I know this must be done in a call server to server. But, I don't know how should I manage the info provided by the Android Spotify SDK to get the refresh_token from the server. I don't even know if this can be achieved via the Spotify SDK or will I have to implement the whole authorization. I've searched info in the web but I can't find info related to this subject. Hope someone can help.
A few months ago I have developed an app which also uses Spotify's services. Since I wanted to query audio features of a song, I had to use Spotify's Web API instead as Spotify's Android SDK hasn't provided such thing yet. When I implemented the app I didn't think about it too much so every time when I need to do queries I'd get the access token again. You can get the token using the following code, inside the json string also comes with a expires_in property that tells you how many seconds the token will expire, therefore it should be easy to achieve what you want with some slight modification.
private String getAccessTokenFromJsonStr(String spotifyJsonStr) throws JSONException {
final String OWM_ACCESS_TOKEN = "access_token";
String accessToken;
try {
JSONObject spotifyJson = new JSONObject(spotifyJsonStr);
accessToken = spotifyJson.getString(OWM_ACCESS_TOKEN);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return accessToken;
}
private String getSpotifyAccessToken(){
String response;
String accessToken;
try {
String serviceURL = "https://accounts.spotify.com/api/token";
URL myURL = new URL(serviceURL);
HttpsURLConnection myURLConnection = (HttpsURLConnection) myURL.openConnection();
String userCredentials = "YOUR_USER_CREDENTIALS:YOUR_USER_CREDENTIALS";
int flags = Base64.NO_WRAP | Base64.URL_SAFE;
byte[] encodedString = Base64.encode(userCredentials.getBytes(), flags);
String basicAuth = "Basic " + new String(encodedString);
myURLConnection.setRequestProperty("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
System.setProperty("http.agent", "");
HashMap postDataParams = new HashMap<String, String>();
postDataParams.put("grant_type", "client_credentials");
OutputStream os = myURLConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
response = "";
int responseCode=myURLConnection.getResponseCode();
Log.d(LOG_TAG, "response code is " + responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
String errLine;
String errResponse = "";
BufferedReader br=new BufferedReader(new InputStreamReader(myURLConnection.getErrorStream()));
while ((errLine=br.readLine()) != null) {
errResponse += errLine;
}
Log.d(LOG_TAG, "error response is " + errResponse);
}
Log.d(LOG_TAG, "response is " + response);
} catch (Exception e){
e.printStackTrace();
}
String accessTokenJsonStr = response.toString();
try {
accessToken = getAccessTokenFromJsonStr(accessTokenJsonStr);
return accessToken;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
Authorization-guide
Basically if you need a refresh token (the token provided by SDK lasts for one hour, and then you have to request another one) you need to use the web api to fetch this token. In this case you would not use the SDK for any part of the authentication process. Technically you don't have to use a server↔server component for the passing secret to Spotify server auth step, it's just best practice (security wise) to avoid hard coding the secret into your app, but technically there is nothing preventing you from doing all the authentication steps app↔spotify server utilizing the pertinent web api calls.
I am developing an android app where user logs on to his/her account. After logging in I will receive XSRF token and Laravel Session Id to recognise the specific user. I have to send these tokens for every request I send to the API's to get the appropriate information. But when I am sending the required details as shown in the image, I am getting HTMl file as response instead of getting JSON Object. I was seriously stuck at this problem. Correct Solution may take forward the whole app.
class RegisterConnection extends AsyncTask<String,String,JSONObject> {
protected JSONObject doInBackground(String... arg0) {
JSONObject output = new JSONObject();
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 5000); //Timeout Limit
HttpResponse response = null;
try {
HttpGet get = new HttpGet(statsURL);
get.setHeader("Accept", "application/json");
CookieStore store = new BasicCookieStore();
BasicClientCookie cookie1 = new BasicClientCookie("XSRF-TOKEN", XSRF);
BasicClientCookie cookie2 = new BasicClientCookie("laravel_session", laravel);
store.addCookie(cookie1);
store.addCookie(cookie2);
client.setCookieStore(store);
response = client.execute(get);
if(response!=null){
InputStream in = response.getEntity().getContent();
String resultstring = Utilities.convertStreamToString(in);
Log.i("Result1", resultstring);
output = new JSONObject(resultstring);
Log.i("Result2", output.toString());
}
} catch(Exception e) {
e.printStackTrace();
try {
output.put("sai","error");
Log.i("MainActivity", output.toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
return output;
}
return output;
}
These are the server requirements
http://imgur.com/OY9Q673
This is the Output received
http://imgur.com/IB5AEcT
As far as I can tell, there is nothing wrong with your Android client code.
You are getting HTML from the server so the main reason could be that your Laravel server is rendering the views and sending you back html instead of JSON. Instead of rendering the views on the server, you should send JSON response on your Laravel server side.
Add Jsoup dependency in your gradle file
implementation 'org.jsoup:jsoup:1.11.2'
Document document = Jsoup.parse("http://imgur.com/IB5AEcT");
Elements el = doc.select("button");
Log.i("..........",""+el.attr("data-invite-details"));
Jsoup tutorial
http://jsoup.org/apidocs/org/jsoup/Jsoup.html
I've searched everywhere on how to make this happen but with no results.
First I need to make a request to a website then send a hash (which I already have) and get a response with some data.
I was able to connect but I'm not able to use the hash key to get the data.
Can anyone help me how to do this using android?
Thanks.
I tried to follow this:Make an HTTP request with android
using a host
The solution:
final HttpClient client = new DefaultHttpClient();
final HttpPost postMethod = new HttpPost(URL);
postMethod.setEntity(new StringEntity(postData, "utf-8"));
String responseData = "";
try {
final HttpResponse response = client.execute(postMethod);
responseData = EntityUtils.toString(response.getEntity(), "utf-8");
} catch(final Exception e) {
// handle exception here
}
This is an example of what you can do:
final String URL = "http://192.168.0.100:8000/myHistory/mobile/?user=";
HttpClient client;
StringBuilder url = new StringBuilder(URL);
url.append(user);
url.append("&pwd=");
url.append(hash);
client = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toString());
HttpResponse response = null;
try {
response = client.execute(get);
} catch (IOException e) {
e.printStackTrace();
}
int status = 0;
status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = "";
try {
data = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
//Here you manipulate the 'data' variable, which is in HTML format.
It depends on which kind of hash you are using (SHA-N, MD5, etc) and the kind of framework you are using to build the server. Try to search on the documentation of your framework which kind of cryptographic hash function is used. Then search on internet an API that implements this cryptographic hash function on your code (e.g., Django uses PBKDF2). After that, you need to define the parameters of this function (salt, number of iterations, password (or hash)). The algorithm calculates the hash (password) using the salt and number of iterations values. So when you are trying to access a server you have to send via HTTP the hash that was generated. If this hash is the same hash generated on the server side, then the authentication is successful.
Hi there i'm creating my first android app and i'm wanting to know what is the best and most efficient way of parsing a JSON Feed from a URL.Also Ideally i want to store it somewhere so i can keep going back to it in different parts of the app. I have looked everywhere and found lots of different ways of doing it and i'm not sure which to go for. In your opinion whats the best way of parsing json efficiently and easily?
I'd side with whatsthebeef on this one, grab the data and then serialize to disk.
The code below shows the first stage, grabbing and parsing your JSON into a JSON Object and saving to disk
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
// Save the JSONOvject
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl"));
out.writeObject( jsonObject );
out.close();
Once you have the JSONObject serialized and save to disk, you can load it back in any time using:
// Load in an object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(getCacheDir(),"")+"cacheFile.srl")));
JSONObject jsonObject = (JSONObject) in.readObject();
in.close();
Your best bet is probably GSON
It's simple, very fast, easy to serialize and deserialize between json objects and POJO, customizable, although generally it's not necessary and it is set to appear in the ADK soon. In the meantime you can just import it into your app. There are other libraries out there but this is almost certainly the best place to start for someone new to android and json processing and for that matter just about everyone else.
If you want to persist you data so you don't have to download it every time you need it, you can deserialize your json into a java object (using GSON) and use ORMLite to simply push your objects into a sqlite database. Alternatively you can save your json objects to a file (perhaps in the cache directory)and then use GSON as the ORM.
This is pretty straightforward example using a listview to display the data. I use very similar code to display data but I have a custom adapter. If you are just using text and data it would work fine. If you want something more robust you can use lazy loader/image manager for images.
Since an http request is time consuming, using an async task will be the best idea. Otherwise the main thread may throw errors. The class shown below can do the download asynchronously
private class jsonLoad extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
// Instantiate a JSON object from the request response
try {
JSONObject jsonObject = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = new File(getApplicationContext().getFilesDir(),"nowList.cache");
try {
file.createNewFile();
FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);
writer.write(result);
writer.flush();
writer.close();
}
catch (IOException e) { e.printStackTrace(); return false; }
}
}
Unlike the other answer, here the downloaded json string itself is saved in file. So Serialization is not necessary
Now loading the json from url can be done by calling
jsonLoad jtask=new jsonLoad ();
jtask.doInBackground("http:www.json.com/urJsonFile.json");
this will save the contents to the file.
To open the saved json string
File file = new File(getApplicationContext().getFilesDir(),"nowList.cache");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//print log
}
JSONObject jsonObject = new JSONObject(text);
I´m creating an android application that stores data in CouchDB, and I need to create a database from the android application. I need to execute the command "curl-X PUT http://user:passwd#127.0.0.1:5984/myDataBase" with java methods.
I have implemented the following functions:
public static boolean createDatabase(String hostUrl, String databaseName) {
try {
HttpPut httpPutRequest = new HttpPut(hostUrl + databaseName);
JSONObject jsonResult = sendCouchRequest(httpPutRequest);
return jsonResult.getBoolean("ok");
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
private static JSONObject sendCouchRequest(HttpUriRequest request) {
try {
HttpResponse httpResponse = (HttpResponse) new DefaultHttpClient().execute(request);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String resultString = convertStreamToString(instream);
instream.close();
JSONObject jsonResult = new JSONObject(resultString);
return jsonResult;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I call the function by:
createDatabase("http://user:passwd#127.0.0.1/","myDataBase");
but there is no result. I think the problem is in user:passwd because in "admin party" mode the funcion works fine calling by:
createDatabase("http://127.0.0.1/","myDataBase");
I had the same problem -> you have to use the HTTP Authentication in the header.
So just add this header lines to your request:
private static void setHeader(HttpRequestBase request) {
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
request.setHeader("Authorization", "Basic base64(username:password)");
}
keep in mind that you have to encode the phrase "username:password" with base64.
this looks something like this:
request.setHeader("Authorization", "Basic 39jdlf9udflkjJKDKeuoijdfoier");
You could have a look at this blogpost on libcouch-android. It has some nice features that really support Android development with CouchDB. For example automatically creating databases and passwords for applications, so users have transparent usage of CouchDB (if wanted).
Also, it is offering access to the RPC methods of CouchDB, so you can start and stop the DB from your application's lifecycles.
Regarding security, I just had this summed up here in this thread.