UnknownHostException WebDav JackRabbit - android

I'm trying to implement a WebDav client in Android. For this purpose, I'm using a version of JackRabbit modified for Android that I got here (version 2.2.6).
I want to connect to my account in box.com and upload a file. Sincerely, I don't mind box or any other, i just happened to use this one.
Well, continuing with box.com, according to (this link)[https://support.box.com/hc/en-us/articles/200519748-Does-Box-support-WebDAV-] I should used "https://dav.box.com/dav" as server.
I have followed these links to build my code:
http://jackrabbit.apache.org/api/2.1/org/apache/jackrabbit/webdav/client/methods/package-summary.html
http://wiki.apache.org/jackrabbit/WebDAV
I'm getting an UnknownHostException sayingo my the URL I'm using for the server ("https://dav.box.com/dav") couldn't be found.
Any idea why does it not work? Otherwise, have you tried with other server and succeeded?
My code is here:
Thread t = new Thread() {
public void run(){
try {
String uri = "https://app.box.com/files";
HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setHost(uri);
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
int maxHostConnections = 20;
params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
connectionManager.setParams(params);
HttpClient client = new HttpClient(connectionManager);
client.setHostConfiguration(hostConfig);
Credentials creds = new UsernamePasswordCredentials("USER", "PASSWORD");
client.getState().setCredentials(AuthScope.ANY, creds);
String baseUrl = "/";
File f = new File(Environment.getExternalStorageDirectory() + "/working-draft.txt");
PutMethod method = new PutMethod(baseUrl + "/" + f.getName());
RequestEntity requestEntity = new InputStreamRequestEntity(
new FileInputStream(f));
method.setRequestEntity(requestEntity);
client.executeMethod(method);
}
catch (FileNotFoundException fnfe){
Log.i("SERVICE", "FileNotFoundException");
}
catch (HttpException he){
Log.i("SERVICE", "HttpException");
}
catch (IOException ioe){
Log.i("SERVICE", "IOException");
}
catch (Exception e){
Log.i("SERVICE", "Other Exception");
}
}
};
t.start();

I tried for a long time with JackRabbit and another webDav library but could not get it to work. This is how I eventually managed to send images to a WebDav hosted in IIS7 on a windows server. Hope this helps somebody.
SendImage.java
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import ntlm.NTLMSchemeFactory;
//import org.apache.http.client.HttpClient;
public class SendImage extends AsyncTask<String, Context, String> {
Context cxt;
public SendImage(Context cxtIn){
cxt = cxtIn;
}
#Override
protected String doInBackground(String... params) {
if (!Globals.sendImagesBeingPerformed) {
Globals.sendImagesBeingPerformed = true;
String filepath = cxt.getExternalFilesDir("/MyFileStorage/qrscans/").getAbsolutePath();
File myExternalFile = new File(filepath.toString());
File[] sdDirList = myExternalFile.listFiles();
if(sdDirList != null && sdDirList.length>0){
for(int x=0;x<sdDirList.length;x++){
if(sdDirList[x].toString().endsWith(".jpg")){
File myExternalFile2 = new File(cxt.getExternalFilesDir("/MyFileStorage/qrscans/"), sdDirList[x].getName());
//String URL="";
System.out.println("SENDING QR4");
if(myExternalFile2.exists()) {
System.out.println("ScannedExists");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
String url = Globals.getWebDavUrl().trim();
String u = Globals.getWebDavUser().trim();
String p = Globals.getWebDavPass().trim();
String d = Globals.getWebDavDomain().trim();
if(d!=null && !d.isEmpty() && (d.length()>0)){
//use value of d as domain
}else{
//use a space as domain
d = " ";
}
String device = Globals.deviceId;
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1),
new NTCredentials(u, p, device, d));
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),5000);
if(url.endsWith("/") || url.endsWith("\\")){
url = url.substring(0, url.length()-1);
}
HttpPut put = new HttpPut(url.trim()+"/"+sdDirList[x].getName());
put.setEntity(new FileEntity(sdDirList[x],"application/octet-stream"));
HttpResponse response = null;
try {
response = httpclient.execute(put);
}catch(Exception e){
return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
}
System.out.println("execute done");
BufferedReader in = null;
String webResponse="";
try {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String stringLine="";
StringBuilder stringBuilder = new StringBuilder();
while ((stringLine = in.readLine()) != null) {
//stringBuilder.append("\n");
stringBuilder.append(stringLine);
}
webResponse=stringBuilder.toString()+"s";
if(webResponse.toString().trim().equalsIgnoreCase("s")){
myExternalFile2.delete();
}
System.out.println("webResponse:" + webResponse);
return null; //webResponse;
}catch(Exception e){
return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
}
}
}
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
if(result!=null){
Toast.makeText(cxt, result, Toast.LENGTH_LONG).show();
}
Globals.sendImagesBeingPerformed = false;
super.onPostExecute(result);
}
}
NTLMSchemeFactory.java
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.impl.auth.NTLMScheme;
import org.apache.http.params.HttpParams;
public class NTLMSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new NTLMScheme(new JCIFSEngine());
}
}
JCIFSEngine.java
package ntlm;
import java.io.IOException;
import jcifs.ntlmssp.Type1Message;
import jcifs.ntlmssp.Type2Message;
import jcifs.ntlmssp.Type3Message;
import jcifs.util.Base64;
import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;
public class JCIFSEngine implements NTLMEngine {
public String generateType1Msg(
String domain,
String workstation) throws NTLMEngineException {
Type1Message t1m = new Type1Message(
Type1Message.getDefaultFlags(),
domain,
workstation);
return Base64.encode(t1m.toByteArray());
}
public String generateType3Msg(
String username,
String password,
String domain,
String workstation,
String challenge) throws NTLMEngineException {
Type2Message t2m;
try {
t2m = new Type2Message(Base64.decode(challenge));
} catch (IOException ex) {
throw new NTLMEngineException("Invalid Type2 message", ex);
}
Type3Message t3m = new Type3Message(
t2m,
password,
domain,
username,
workstation,0);
return Base64.encode(t3m.toByteArray());
}
}

Related

GetCoockie from appengine

hey i've written a server in app engine. i've used so far the HttpDefaultClient in order to do so.
protected Boolean doInBackground(String... tokens) {
try {
// Don't follow redirects
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpGet httpGet = new HttpGet("http://" + appId
+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + tokens[0]);
response = httpclient.execute(httpGet);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
if(response.getStatusLine().getStatusCode() != 302){
// Response should be a redirect
return false;
}
//check if we received the ACSID or the SACSID cookie, depends on http or https request
for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
if(cookie.getName().equals("ACSID") || cookie.getName().equals("SACSID")){
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
} finally {
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
}
return false;
}
does any one knows how do i get the same coockie via other connection??
i know how to recieve the token : by httpUrlconnection:
private String getAuthToken() {
AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(
mAccount, "ah", null, true, null, null);
Bundle bundle;
try {
bundle = future.getResult(10, TimeUnit.SECONDS);
} catch (OperationCanceledException | IOException | AuthenticatorException e) {
Log.e(TAG, "Unexpected error while getting an auth token: ", e);
throw new RuntimeException(e);
}
return bundle.getString(AccountManager.KEY_AUTHTOKEN);
}
:
private URL getAuthUrl(String token) {
api = "http://" + appId+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + token;
String path = Uri.parse(mBaseUrl)
.buildUpon()
.appendEncodedPath("_ah/login")
.appendQueryParameter("continue", mBaseUrl)
.appendQueryParameter("auth", token)
.build()
.toString();
try {
return new URL(api);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
private String getAuthCookie(URL authUrl) {
HttpURLConnection conn = ((HttpURLConnection) authUrl.openConnection());
String cookie = conn.getHeaderField("Set-Cookie"); // returns null!
return cookie;
}
any idea why?? and how to fix it?
i've recieved : NID=72=bIkTJcJ1o1iX988WeqjEhAELifvxtDOoD0sIe-VqZQK0ToezFvDSx0ctjko8KZyJYA7S1aAyl-7WYh6Wue-UHhSJYgXSQg9NrFXEMjUujONGIomcrSsX5373zYb59oBI; expires=Thu, 07-Apr-2016 22:56:30 GMT; path=/; domain=.google.com; HttpOnly
answer :
package com.example.daniel.testing9;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* AppEngine authentication with a Google account works as follows:
1. First we obtain a token from the Google account on device.
2. We authenticate with Appengine at /_ah/login URL
3. If authentication is successful, an ACSID (SACSID for https) cookie is set
4. If the token has expired (default 24 hours), then we invalidate it and try again.
5. Set the [S]ACSID cookie on future requests, e.g.:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
*/
public class AuthHelper {
private static final String TAG = "auth";
public static boolean finished = false;
private final AccountManager mAccountManager;
private final Account mAccount;
private final String mBaseUrl;
private static String _cookie = null;
String appId;
String api;
String token;
static AuthHelper instance = null;
public static AuthHelper getInstance() {
if (instance == null) {
AccountManager accountManager = AccountManager.get(MainActivity.context.getApplicationContext());
accountManager = AccountManager.get(MainActivity.context.getApplicationContext());
// assembling all gmail accounts
Account[] accounts = accountManager.getAccountsByType("com.google");
// add all gmail accounts :
ArrayList<String> accountList = new ArrayList<String>();
for (Account account : accounts) {
accountList.add(account.name);
}
Account account = accounts[0];
instance = new AuthHelper(accountManager, account, Constants.SERVER_REQUESTS.MY_APP_WEBSITE,
Constants.SERVER_REQUESTS.MY_APP_ID);
}
return instance;
}
public AuthHelper(#NonNull AccountManager accountManager,
#NonNull Account account,
#NonNull String appspotBaseUrl, String appid) {
mAccountManager = accountManager;
mAccount = account;
mBaseUrl = appspotBaseUrl;
this.appId = appid;
}
public String getAuthPath(String url) {
if (token == null) {
token = getAuthToken();
}
return api = Constants.SERVER_REQUESTS.MY_APP_WEBSITE+"_ah/login?continue="+url+"&auth=" + token;
}
public String authenticateAndGetCookie() {
for (int i = 0; i < 2; i++) {
token = getAuthToken();
URL authUrl = getAuthUrl(token);
String cookie = getAuthCookie(authUrl);
if (cookie != null) {
_cookie = cookie;
return cookie;
}
invalidateAuthToken(token);
}
return null;
}
private String getAuthCookie(URL authUrl) {
try {
HttpURLConnection conn = ((HttpURLConnection) authUrl.openConnection());
return conn.getHeaderField("Set-Cookie");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private URL getAuthUrl(String token) {
api = "http://" + appId+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + token;
String path = Uri.parse(mBaseUrl)
.buildUpon()
.appendEncodedPath("_ah/login")
// .appendQueryParameter("continue", mBaseUrl)
.appendQueryParameter("auth", token)
.build()
.toString();
try {
return new URL(path);
//return new URL(api);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
private String getAuthToken() {
AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(
mAccount, "ah", null, true, null, null);
Bundle bundle;
try {
bundle = future.getResult(10, TimeUnit.SECONDS);
} catch (OperationCanceledException | IOException | AuthenticatorException e) {
Log.e(TAG, "Unexpected error while getting an auth token: ", e);
throw new RuntimeException(e);
}
return bundle.getString(AccountManager.KEY_AUTHTOKEN);
}
private void invalidateAuthToken(String token) {
mAccountManager.invalidateAuthToken(mAccount.type, token);
finished = true;
}
}

Twitter's live streaming API unauthorized(android)

I found this old android example code that can filter tweets from Twitter's live streaming API according to the input of user, but the problem is that it uses the basic authorization.
Obviously it wouldn't work and I got the "401 unauthorized" error.
Here is the original code:
package com.teleknesis.android.twitter.livestream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class TwitterLiveStreamingActivity extends Activity {
private List<HashMap<String,String>> mTweets = new ArrayList<HashMap<String,String>>();
private SimpleAdapter mAdapter;
private boolean mKeepRunning = false;
private String mSearchTerm = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAdapter = new SimpleAdapter(this, mTweets, android.R.layout.simple_list_item_2, new String[] {"Tweet", "From"}, new int[] {android.R.id.text1, android.R.id.text2});
((ListView)findViewById(R.id.Tweets)).setAdapter(mAdapter);
}
public void startStop( View v ) {
if( ((Button)v).getText().equals("Start") ) {
mSearchTerm = ((EditText)findViewById(R.id.SearchText)).getText().toString();
if( mSearchTerm.length() > 0 ) {
new StreamTask().execute();
mKeepRunning = true;
((Button)v).setText("Stop");
}
else {
Toast.makeText(this, "You must fill in a search term", Toast.LENGTH_SHORT).show();
}
}
else {
mKeepRunning = false;
((Button)v).setText("Start");
}
}
private class StreamTask extends AsyncTask<Integer, Integer, Integer> {
private String mUrl = "https://stream.twitter.com/1/statuses/filter.json?track=";
#Override
protected Integer doInBackground(Integer... params) {
try {
DefaultHttpClient client = new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials("username", "password");
client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
HttpGet request = new HttpGet();
request.setURI(new URI("https://stream.twitter.com/1/statuses/filter.json?track=" + mSearchTerm));
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
parseTweets(reader);
in.close();
}
catch (Exception e) {
Log.e("Twitter", "doInBackground_" + e.toString());
}
return new Integer(1);
}
private void parseTweets( BufferedReader reader ) {
try {
String line = "";
do {
line = reader.readLine();
Log.d("Twitter", "Keep Running: " + mKeepRunning
+ " Line: " + line);
JSONObject tweet = new JSONObject(line);
HashMap<String, String> tweetMap = new HashMap<String, String>();
if (tweet.has("text")) {
tweetMap.put("Tweet", tweet.getString("text"));
tweetMap.put("From", tweet.getJSONObject("user")
.getString("screen_name"));
mTweets.add(0, tweetMap);
if (mTweets.size() > 10) {
mTweets.remove(mTweets.size() - 1);
}
//mAdapter.notifyDataSetChanged();
publishProgress(1);
}
} while (mKeepRunning && line.length() > 0);
}
catch (Exception e) {
// TODO: handle exception
}
}
protected void onProgressUpdate(Integer... progress) {
mAdapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Integer i) {
}
}
}
I try to replace the credential with the OAuth:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("*************");
cb.setOAuthConsumerSecret("*************");
cb.setOAuthAccessToken("*************");
cb.setOAuthAccessTokenSecret("*************");
Didn't work..(I have all the correct keys and secrets)
I also tried to insert this whole part into one currently operational twitter client(I can get all the tweets on timeline and all), I don't know if I did it right but it didn't work either. Also in this case, if the Oauth was done again in this code and it worked, does that mean when I run the application I have to be redirected to the authorization page twice if I wanted to use this filter function? I would love a fix that the twitter feed can be used by both the timeline and this filtering mode.
Would anybody shed some lights on how I can do this?
Problem solved.
Here is the modified code:
protected Integer doInBackground(Integer... params) {
try {
DefaultHttpClient client = new DefaultHttpClient();
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
consumer.setTokenWithSecret(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
HttpGet request = new HttpGet();
request.setURI(new URI("https://stream.twitter.com/1/statuses/filter.json?track=" + mSearchTerm));
consumer.sign(request);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
parseTweets(reader);
in.close();
}

Instagram feed search android

I need some help on Instagram api in android development, i need to search feeds or tags of Instagram in my app, is any one have suggestion about on it? or please provide links of tutorial
Advance thanks
You can find all you need on the instagram developer page:
http://instagram.com/developer/endpoints/tags/
Instagram provides a RESTful API, so you will make simple HTTP-calls on URLs with your specified parameters (like a tag you want to search for). The response will be in JSON-format, from which you can extract the desired information such as image urls, user-name, etc.
With the bold parts above you have all you need reach your goal. Just google for these parts, here is a tutorial for implementing REST in Android. Also see this question on StackOverflow to reach a more advanced implementation: Android rest client sample.
Also Vogella's tutorial is great and shows you both parts, the request call and the response parsing.
Here is a function that creates the URl to search for a certain hashtag:
public static String getSearchUrl(String hashtag) {
return "https://api.instagram.com/v1/tags/" + hashtag
+ "/media/recent?client_id=" + Constants.CLIENT_ID;
}
package com.pgd.Fragments;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.pgd.Adepters.InstagramTimelineAdapter;
import com.pgd.Beans.InstagramBeans;
import com.pgd.R;
import com.pgd.SocialLogin.Params;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
/**
* Created by admin on 9/26/2017.
*/
public class InstagramTimelineFragment extends Fragment {
public static final String API_AUTH_URL = "https://instagram.com/oauth/authorize/?";
public static final String API_ACCESS_TOKEN_URL = "https://api.instagram.com/oauth/access_token";
public static final String API_BASE_URL = "https://api.instagram.com/v1";
public String CLIENT_ID = "8c1e17fd79e1402e915d94c1f05c5c3c";
public String CLIENT_SECRET = "8885809e2b934647bedcec7068ea3e78";
public String REDIRECT_URL = "https://stackoverflow.com/users/6286004/amit-bhatnagar";
String username = "";
String fullName = "";
String profilePicture = "";
String accessToken = "";
String id = "";
private WebView _webView;
private LinearLayout _loadProgressLayout;
private ProgressBar _loadProgressBar;
InstagramBeans instagramBeansList;
InstagramTimelineAdapter instagramTimelineAdapter;
private RecyclerView recyclerView;
public static final String InstagramTimelineFragment = "InstagramTimelineFragment";
public static InstagramTimelineFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(InstagramTimelineFragment, page);
InstagramTimelineFragment fragment = new InstagramTimelineFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.instagram_timeline_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.insta_recyclerView);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
initWebView(view);
return view;
}
private void initWebView(View view) {
_loadProgressBar = (ProgressBar) view.findViewById(R.id.loadProgressBar);
_loadProgressLayout = (LinearLayout) view.findViewById(R.id.loadProgressLayout);
_webView = (WebView) view.findViewById(R.id.webView);
_webView.getSettings().setJavaScriptEnabled(true);
_webView.clearCache(true);
_webView.setWebViewClient(new InstagramWebViewClient());
_webView.setWebChromeClient(new InstagramWebChromeClient());
CookieSyncManager.createInstance(getActivity());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
_webView.loadUrl(getCodeRequest(CLIENT_ID, REDIRECT_URL));
}
public String authorize(String clientId, String clientSecret, String redirectUrl, String code) throws IOException, JSONException {
Params params = new Params();
params.put("client_id", clientId);
params.put("client_secret", clientSecret);
params.put("redirect_uri", redirectUrl);
params.put("grant_type", "authorization_code");
params.put("code", code);
JSONObject rootJson = sendRequest(API_ACCESS_TOKEN_URL, params, Request.POST);
JSONObject userJson = rootJson.getJSONObject("user");
id = userJson.getString("id");
username = userJson.optString("username");
fullName = userJson.optString("full_name");
profilePicture = userJson.optString("profile_picture");
accessToken = rootJson.optString("access_token");
Log.d("name", username);
return accessToken;
}
public JSONObject sendRequest(String url, Params params, Request request) throws IOException, JSONException {
String signedUrl = getSignedUrl(url, params, request);
String body = "";
if (request == Request.POST)
body = params.getParamsStringUtf8();
System.out.println("Tag" + " url : " + signedUrl);
if (body.length() != 0)
System.out.println("Tag" + " body : " + body);
String response = "";
for (int i = 1; i <= 3; ++i) {
try {
if (i != 1)
System.out.println("tag" + " try send = " + i);
response = sendDummyRequest(signedUrl, body, request);
break;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// JSONObject rootJSON = new JSONObject(response);
JSONObject rootJSON = (JSONObject) new JSONTokener(response).nextValue();
return rootJSON;
}
public enum Request {
GET,
POST
}
private String sendDummyRequest(String url, String body, Request request) throws IOException {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setUseCaches(false);
connection.setDoInput(true);
// connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
if (request == Request.GET) {
connection.setDoOutput(false);
connection.setRequestMethod("GET");
} else if (request == Request.POST) {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
}
if (false)
connection.setRequestProperty("Accept-Encoding", "gzip");
if (request == Request.POST)
connection.getOutputStream().write(body.getBytes("utf-8"));
int code = connection.getResponseCode();
System.out.println("TAG" + " responseCode = " + code);
//It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
if (code == -1)
throw new IOException();
//может стоит проверить на код 200
//on error can also read error stream from connection.
InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192);
String encoding = connection.getHeaderField("Content-Encoding");
if (encoding != null && encoding.equalsIgnoreCase("gzip"))
inputStream = new GZIPInputStream(inputStream);
String response = convertStreamToString(inputStream);
System.out.println("TAG" + " response = " + response);
return response;
} finally {
if (connection != null)
connection.disconnect();
}
}
private String getSignedUrl(String url, Params params, Request request) {
String signedUrl = url + params.getEndpoint();
if (request == Request.GET) {
String args = params.getParamsStringUtf8();
return signedUrl + "?" + args;
}
return signedUrl;
}
public String convertStreamToString(InputStream is) throws IOException {
InputStreamReader r = new InputStreamReader(is);
StringWriter sw = new StringWriter();
char[] buffer = new char[1024];
try {
for (int n; (n = r.read(buffer)) != -1; )
sw.write(buffer, 0, n);
} finally {
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return sw.toString();
}
public class InstagramWebViewClient extends WebViewClient {
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(REDIRECT_URL)) {
final Intent intent = new Intent();
if (url.contains("code")) {
String temp[] = url.split("=");
final String code = temp[1];
new Thread(new Runnable() {
#Override
public void run() {
try {
accessToken = authorize(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, code);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// getFeed();
// userNameTextView.setText(username);
//userFullnameTextView.setText(fullName);
//Picasso.with(getActivity()).load(profilePicture).into(userImageView);
_webView.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
getFeed();
}
});
} catch (final Exception e) {
e.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
intent.putExtra("error", e.getMessage());
// setResult(Activity.RESULT_OK, intent);
// finish();
}
});
}
}
}).start();
} else if (url.contains("error")) {
String temp[] = url.split("=");
String error = temp[temp.length - 1];
intent.putExtra("error", error);
// setResult(Activity.RESULT_OK, intent);
// finish();
}
return true;
}
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
_loadProgressLayout.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
_loadProgressLayout.setVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
_loadProgressLayout.setVisibility(View.GONE);
Toast.makeText(getActivity(),
getString(R.string.page_load_error),
Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("error", description);
// setResult(Activity.RESULT_OK, intent);
//finish();
}
}
public String getCodeRequest(String clientId, String redirectUrl) {
return API_AUTH_URL + "client_id=" + clientId + "&redirect_uri=" + redirectUrl + "&response_type=code";
}
private class InstagramWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
_loadProgressBar.setProgress(newProgress);
}
}
public void getFeed() {
try {
URL example = new URL("https://api.instagram.com/v1/users/self/media/recent?access_token="
+ accessToken);
Ion.with(getActivity())
.load(String.valueOf(example))
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
// do stuff with the result or error
String response = result.toString();
Log.d("res_feed", response);
Gson gson = new Gson();
instagramBeansList = gson.fromJson(response, InstagramBeans.class);
if (instagramBeansList.getData().size() > 0) {
instagramTimelineAdapter = new InstagramTimelineAdapter(getActivity(), instagramBeansList.getData());
recyclerView.setAdapter(instagramTimelineAdapter);
} else {
Toast.makeText(getActivity(), "Data in empty", Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
} else {
}
}
}

android: hide progressdialog whe the app regain control

I've an app that opens the facebook app when you click on a button, it works fine but on slow devices (like mine) facebook takes some seconds to show up, so i want to add a simple progressdialog that says "please wait"
i can show the progress dialog and open facebook with this code:
final ProgressDialog pd = ProgressDialog.show(contatti.this, "", "Attendere...", true);
Intent facebookIntent = getOpenFacebookIntent(getApplicationContext());
startActivity(facebookIntent);
//pd.dismiss();
the first time i tried, it worked fine but when i went back from facebook to my app the dialog was still showing, and i had no way to close it.
added dismiss() to try hide it, but it was a stupid idea >.<
how can i dismiss the dialog when the app regain control?
For this situation you have to check whether the application is sent background or not in on pause if it sent to background then close the dialog.
for checking the application is in bacground or not just have a look
android:how to check if application is running in background
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.gvsu.cis.toptracks.R;
import edu.gvsu.cis.toptracks.TopTrackListActivity;
import edu.gvsu.cis.toptracks.data.Customer;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class LastWebAPITask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private TopTrackListActivity activity;
private static final String debugTag = "LastWebAPITask";
public LastWebAPITask(TopTrackListActivity activity) {
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_tracks), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
Log.d(debugTag, "Background:" + Thread.currentThread().getName());
String result = LastHelper.downloadFromServer(params);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<Customer> trackdata = new ArrayList<Customer>();
progDialog.dismiss();
if (result.length() == 0) {
this.activity.alert("Unable to find track data. Try again later.");
return;
}
try {
JSONObject respObj = new JSONObject(result);
JSONArray tracks = respObj.getJSONArray("GetStockListResult");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String Inventory_Status = track.getString("Inventory_Status");
String modify_Date = track.getString("modify_Date");
String msg = track.getString("msg");
String serial_nbr = track.getString("serial_nbr");
;
trackdata
.add(new Customer(Inventory_Status, modify_Date, msg, serial_nbr));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.activity.setTracks(trackdata);
}
}
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class LastHelper {
private static final String LastUrl = "http://etosxmldev.ctdi.com/ws/wcf/UNIVERSAL-DEMO/Service.svc/GetStockList?LocationId=300779360.svc/GetStockList/1111";
private static final int HTTP_STATUS_OK = 200;
private static byte[] buff = new byte[1024];
private static final String logTag = "LastHelper";
public static class ApiException extends Exception {
private static final long serialVersionUID = 1L;
public ApiException(String msg) {
super(msg);
}
public ApiException(String msg, Throwable thr) {
super(msg, thr);
}
}
protected static synchronized String downloadFromServer(String... params)
throws ApiException {
String retval = null;
String url = LastUrl;
Log.d(logTag, "Fetching " + url);
// create an http client and a request object.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
// execute the request
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != HTTP_STATUS_OK) {
// handle error here
throw new ApiException("Invalid response from last.fm"
+ status.toString());
}
// process the content.
HttpEntity entity = response.getEntity();
InputStream ist = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
int readCount = 0;
while ((readCount = ist.read(buff)) != -1) {
content.write(buff, 0, readCount);
}
retval = new String(content.toByteArray());
} catch (Exception e) {
throw new ApiException("Problem connecting to the server "
+ e.getMessage(), e);
}
return retval;
}
}
U have to use Asynctask class for doing this.Working Example for me.in your Activity class
LastWebAPITask lfmTask = new LastWebAPITask(
TopTrackListActivity.this);
lfmTask.execute(metroTxt);
thanks to another forum. looks like the fastest and simple way to do this is using onResume():
#Override
public void onResume(){
super.onResume();
if(waitdialog != null){ //check if we are resuming (not coming from another activity)
if (waitdialog.isShowing()) { //check if is showing
waitdialog.dismiss(); //dismiss
}
}
}

android consumption of navision web service

I need to consume the NAV web service from android.
I got the "Letters" codeunit with "Upper" function.
I have setup a NAV web service (NTLM authentication) on my PC and turned off the firewall (so that this service is visible on other devices in my network). The service can be accessed in the browser (also on the adroid device) after inputting the login/pass (of my PC account).
If i use this code it crashes on "call" with END_DOCUMENT null exception...
Is that because of the authentication?
If i use this code to connect
HttpGet request = new
HttpGet("http://[myPC'sIP]:7047/DynamicsNAV/WS/SystemService");
HttpResponse response = client.execute(request);
i get 401 error, but just specifying the IP
HttpGet request = new HttpGet("http://[myPC'sIP]");
HttpResponse response = client.execute(request);
returns code 200 (ok)
How can I send the credentials? I tried several ways, but result is always the same...
Do you have experience with this issue?
I use soap_action for doing the same and its working like charm, see if below code helps you:
String namespace = "urn:microsoft-dynamics-schemas/codeunit/NavisionWS";
String url = "http://IP:7047/DynamicsNAV/WS/Codeunit/NavisionWS";
String soap_action = "urn:microsoft-dynamics-schemas/codeunit/NavisionWS:GetLoginInfo";
String method_name = "GetLoginInfo";
try
{
SoapObject request = new SoapObject(namespace, method_name);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transport = new HttpTransportSE(url);
transport.call(soap_action, envelope); // Receive Error here!
SoapObject result = (SoapObject) envelope.getResponse();
great = result.toString();
}
catch (Exception e)
{
e.printStackTrace();
great = e.toString();
Toast.makeText(this, great, Toast.LENGTH_LONG).show();
}
1) Add Below Jars
jcifs-1.3.17.jar
ksoap2-android-assembly-3.0.0-jar-with-dependencies.jar
2) Create these java classes
JCIFSEngine.java
package com.demo.Authentication;
import jcifs.ntlmssp.NtlmFlags;
import jcifs.ntlmssp.Type1Message;
import jcifs.ntlmssp.Type2Message;
import jcifs.ntlmssp.Type3Message;
import jcifs.util.Base64;
import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;
import java.io.IOException;
/**
* Class taken from http://hc.apache.org/httpcomponents-client-ga/ntlm.html
*/
public final class JCIFSEngine implements NTLMEngine {
private static final int TYPE_1_FLAGS =
NtlmFlags.NTLMSSP_NEGOTIATE_56 |
NtlmFlags.NTLMSSP_NEGOTIATE_128 |
NtlmFlags.NTLMSSP_NEGOTIATE_NTLM2 |
NtlmFlags.NTLMSSP_NEGOTIATE_ALWAYS_SIGN |
NtlmFlags.NTLMSSP_REQUEST_TARGET;
public String generateType1Msg(final String domain, final String workstation)
throws NTLMEngineException {
final Type1Message type1Message = new Type1Message(TYPE_1_FLAGS, domain, workstation);
return Base64.encode(type1Message.toByteArray());
}
public String generateType3Msg(final String username, final String password,
final String domain, final String workstation, final String challenge)
throws NTLMEngineException {
Type2Message type2Message;
try {
type2Message = new Type2Message(Base64.decode(challenge));
} catch (final IOException exception) {
throw new NTLMEngineException("Invalid NTLM type 2 message", exception);
}
final int type2Flags = type2Message.getFlags();
final int type3Flags = type2Flags
& (0xffffffff ^ (NtlmFlags.NTLMSSP_TARGET_TYPE_DOMAIN | NtlmFlags.NTLMSSP_TARGET_TYPE_SERVER));
final Type3Message type3Message = new Type3Message(type2Message, password, domain,
username, workstation, type3Flags);
return Base64.encode(type3Message.toByteArray());
}
}
NtlmTransport.java
package com.demo.Authentication;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.auth.NTLMScheme;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.ServiceConnection;
import org.ksoap2.transport.Transport;
import org.xmlpull.v1.XmlPullParserException;
public class NtlmTransport extends Transport {
static final String ENCODING = "utf-8";
private final DefaultHttpClient client = new DefaultHttpClient();
private final HttpContext localContext = new BasicHttpContext();
private String urlString;
private String user;
private String password;
private String ntDomain;
private String ntWorkstation;
public static String AuthenticationCode;
public NtlmTransport(String url, String user, String password,
String domain, String workStation) {
this.urlString = url;
this.user = user;
this.password = password;
this.ntDomain = domain;
this.ntWorkstation = workStation;
}
public void setCredentials(String url, String user, String password,
String domain, String workStation) {
this.urlString = url;
this.user = user;
this.password = password;
this.ntDomain = domain;
this.ntWorkstation = workStation;
}
public List call(String targetNamespace, SoapEnvelope envelope, List headers)
throws IOException, XmlPullParserException {
return call(targetNamespace, envelope, headers, null);
}
public List call(String soapAction, SoapEnvelope envelope, List headers, File outputFile)
throws IOException, XmlPullParserException {
if (outputFile != null) {
// implemented in HttpTransportSE if you are willing to port..
throw new RuntimeException("Writing to file not supported");
}
HttpResponse resp = null;
setupNtlm(urlString, user, password);
try {
// URL url = new URL(urlString);
HttpPost httppost = new HttpPost(urlString);
setHeaders(soapAction, envelope, httppost, headers);
resp = client.execute(httppost, localContext);
HttpEntity respEntity = resp.getEntity();
InputStream is = respEntity.getContent();
parseResponse(envelope, is);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("RESPONSE STATUS CODE :"+resp.getStatusLine().getStatusCode());
if (resp != null) {
return Arrays.asList(resp.getAllHeaders());
} else {
return null;
}
}
private void setHeaders(String soapAction, SoapEnvelope envelope, HttpPost httppost, List headers) {
byte[] requestData = null;
try {
requestData = createRequestData(envelope);
} catch (IOException iOException) {
}
ByteArrayEntity byteArrayEntity = new ByteArrayEntity(requestData);
httppost.setEntity(byteArrayEntity);
httppost.addHeader("User-Agent", org.ksoap2.transport.Transport.USER_AGENT);
// SOAPAction is not a valid header for VER12 so do not add
// it
// #see "http://code.google.com/p/ksoap2-android/issues/detail?id=67
if (envelope.version != SoapSerializationEnvelope.VER12) {
httppost.addHeader("SOAPAction", soapAction);
}
if (envelope.version == SoapSerializationEnvelope.VER12) {
httppost.addHeader("Content-Type", Transport.CONTENT_TYPE_SOAP_XML_CHARSET_UTF_8);
} else {
httppost.addHeader("Content-Type", Transport.CONTENT_TYPE_XML_CHARSET_UTF_8);
}
// Pass the headers provided by the user along with the call
if (headers != null) {
for (int i = 0; i < headers.size(); i++) {
HeaderProperty hp = (HeaderProperty) headers.get(i);
httppost.addHeader(hp.getKey(), hp.getValue());
}
}
}
// Try to execute a cheap method first. This will trigger NTLM authentication
public void setupNtlm(String dummyUrl, String userId, String password) {
try {
((AbstractHttpClient) client).getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
NTCredentials creds = new NTCredentials(userId, password, ntWorkstation, ntDomain);
client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
HttpGet httpget = new HttpGet(dummyUrl);
HttpResponse response1 = client.execute(httpget, localContext);
HttpEntity entity1 = response1.getEntity();
Header[] hArray = response1.getAllHeaders();
int size = hArray.length;
AuthenticationCode = String.valueOf(response1.getStatusLine().getStatusCode());
System.out.println("AUTHENTICATION STATUS CODE :"+response1.getStatusLine().getStatusCode());
/* for (int i = 0; i < size; i ++) {
Header h = hArray[i];
if (h.getName().equals("WWW-Authenticate")) {
entity1.consumeContent();
throw new Exception("Failed Authentication");
}
}*/
entity1.consumeContent();
} catch (Exception ex) {
ex.printStackTrace();
}
}
//NTLM Scheme factory
private class NTLMSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
// see http://www.robertkuzma.com/2011/07/
// manipulating-sharepoint-list-items-with-android-java-and-ntlm-authentication/
return new NTLMScheme(new JCIFSEngine());
}
}
public ServiceConnection getServiceConnection() throws IOException
{
throw new IOException("Not using ServiceConnection in transport");
}
public String getHost() {
String retVal = null;
try {
retVal = new URL(url).getHost();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return retVal;
}
public int getPort() {
int retVal = -1;
try {
retVal = new URL(url).getPort();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return retVal;
}
public String getPath() {
String retVal = null;
try {
retVal = new URL(url).getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return retVal;
}
}
3)
Call this method with paramater url,"username","password","domainName","SystemName"
NtlmTransport ntlm = new NtlmTransport(url, "username", "password", "domainName","SystemName");
4) Send Soap Request which consist of Soap Envelope.
ntlm.call("namespace/methodname", soapEnvelope);
Solved by creation of another web service (written on C#, running on the same PC where NAV server runs) which reads NAV service and android communicates with NAV WS through this C# WS
Hi have you tried to use
var httpClient = new DefaultHttpClient();
NTCredentials nt = new NTCredentials("user", "pass", "", "domain");
httpClient.GetCredentialsProvider().SetCredentials(AuthScope.ANY, nt);
This is how http authentication is supposed to work. You can use fiddler to see what your intermediary is doing. If you want to get rid of it you'll have to do the same thing :)
That being said authentication with Navision is no picnic as it uses SPNEGO or NTLM. If you can configure for NTLM you might be able to use android-ntlm to get the job done. Looks similar to pungggi's answer except for httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());

Categories

Resources