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;
}
}
Related
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());
}
}
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 {
}
}
}
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());
i am uploading video to youtube which by default uploads to user who have login in google account.
But i want to set that all video should upload using my static gmailID and password
Is it possible to Login in google account directly using static emailid and password ?
Or any other good api or example to upload video in youtube.
Thanks in advance....
I have wrapped uploading feature from project referred in MAC'S answer into single utility class :
Here is YoutubeUploader.java
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore.Video;
import android.util.Log;
public class YoutubeUploader {
private static final String TAG = "YoutubeUploader";
// After creating project at http://www.appspot.com DEFAULT_YTD_DOMAIN == <Developers Console Project ID>.appspot.com [ You can find from Project -> Administration -> Application settings]
public static final String DEFAULT_YTD_DOMAIN = "developerconsolid.appspot.com";
// I used Google APIs Console Project Title as Domain name:
public static final String DEFAULT_YTD_DOMAIN_NAME = "Domain Name";
//From Google Developer Console from same project (Created by SHA1; project package)
//Example https://console.developers.google.com/project/apps~gtl-android-youtube-test/apiui/credential
public static final String DEVELOPER_KEY = "developer key";
// CLIENT_ID == Google APIs Console Project Number:
public static final String CLIENT_ID = "client_id";
public static final String YOUTUBE_AUTH_TOKEN_TYPE = "youtube";
private static final String AUTH_URL = "https://www.google.com/accounts/ClientLogin";
// Uploader's user-name and password
private static final String USER_NAME = "usersemail#useremail.usersemail";
private static final String PASSWORD = "userspassword";
private static final String INITIAL_UPLOAD_URL = "https://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads";
private static String getClientAuthToken() {
try {
URL url = new URL(AUTH_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String template = "Email=%s&Passwd=%s&service=%s&source=%s";
String userName = USER_NAME; // TODO
String password = PASSWORD; // TODO
String service = YOUTUBE_AUTH_TOKEN_TYPE;
String source = CLIENT_ID;
userName = URLEncoder.encode(userName, "UTF-8");
password = URLEncoder.encode(password, "UTF-8");
String loginData = String.format(template, userName, password, service, source);
OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
outStreamWriter.write(loginData);
outStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode != 200) {
Log.d(TAG, "Got an error response : " + responseCode + " " + urlConnection.getResponseMessage());
throw new IOException(urlConnection.getResponseMessage());
} else {
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("Auth=")) {
String split[] = line.split("=");
String token = split[1];
Log.d(TAG, "Auth Token : " + token);
return token;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String upload(YoutubeUploadRequest uploadRequest, ProgressListner listner, Activity activity) {
totalBytesUploaded = 0;
String authToken = getClientAuthToken();
if(authToken != null) {
String uploadUrl = uploadMetaData(uploadRequest, authToken, activity, true);
File file = getFileFromUri(uploadRequest.getUri(), activity);
long currentFileSize = file.length();
int uploadChunk = 1024 * 1024 * 3; // 3MB
int start = 0;
int end = -1;
String videoId = null;
double fileSize = currentFileSize;
while (fileSize > 0) {
if (fileSize - uploadChunk > 0) {
end = start + uploadChunk - 1;
} else {
end = start + (int) fileSize - 1;
}
Log.d(TAG, String.format("start=%s end=%s total=%s", start, end, file.length()));
try {
videoId = gdataUpload(file, uploadUrl, start, end, authToken, listner);
fileSize -= uploadChunk;
start = end + 1;
} catch (IOException e) {
Log.d(TAG,"Error during upload : " + e.getMessage());
}
}
if (videoId != null) {
return videoId;
}
}
return null;
}
public static int totalBytesUploaded = 0;
#SuppressLint("DefaultLocale")
#SuppressWarnings("resource")
private static String gdataUpload(File file, String uploadUrl, int start, int end, String clientLoginToken, ProgressListner listner) throws IOException {
int chunk = end - start + 1;
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
FileInputStream fileStream = new FileInputStream(file);
URL url = new URL(uploadUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Authorization", String.format("GoogleLogin auth=\"%s\"", clientLoginToken));
urlConnection.setRequestProperty("GData-Version", "2");
urlConnection.setRequestProperty("X-GData-Client", CLIENT_ID);
urlConnection.setRequestProperty("X-GData-Key", String.format("key=%s", DEVELOPER_KEY));
// some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(chunk);
urlConnection.setRequestProperty("Content-Type", "video/3gpp");
urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end,
file.length()));
Log.d(TAG, urlConnection.getRequestProperty("Content-Range"));
OutputStream outStreamWriter = urlConnection.getOutputStream();
fileStream.skip(start);
double currentFileSize = file.length();
int bytesRead;
int totalRead = 0;
while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
outStreamWriter.write(buffer, 0, bytesRead);
totalRead += bytesRead;
totalBytesUploaded += bytesRead;
double percent = (totalBytesUploaded / currentFileSize) * 100;
if(listner != null){
listner.onUploadProgressUpdate((int) percent);
}
System.out.println("GTL You tube upload progress: " + percent + "%");
/*
Log.d(LOG_TAG, String.format(
"fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
totalBytesUploaded, percent));
*/
//dialog.setProgress((int) percent);
// TODO My settings
if (totalRead == (end - start + 1)) {
break;
}
}
outStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "responseCode=" + responseCode);
Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage());
try {
if (responseCode == 201) {
String videoId = parseVideoId(urlConnection.getInputStream());
return videoId;
} else if (responseCode == 200) {
Set<String> keySet = urlConnection.getHeaderFields().keySet();
String keys = urlConnection.getHeaderFields().keySet().toString();
Log.d(TAG, String.format("Headers keys %s.", keys));
for (String key : keySet) {
Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
}
Log.w(TAG, "Received 200 response during resumable uploading");
throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode,
urlConnection.getResponseMessage()));
} else {
if ((responseCode + "").startsWith("5")) {
String error = String.format("responseCode=%d responseMessage=%s", responseCode,
urlConnection.getResponseMessage());
Log.w(TAG, error);
// TODO - this exception will trigger retry mechanism to kick in
// TODO - even though it should not, consider introducing a new type so
// TODO - resume does not kick in upon 5xx
throw new IOException(error);
} else if (responseCode == 308) {
// OK, the chunk completed succesfully
Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
urlConnection.getResponseMessage()));
} else {
// TODO - this case is not handled properly yet
Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
urlConnection.getResponseMessage(), uploadUrl));
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
private static String parseVideoId(InputStream atomDataStream) throws ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(atomDataStream);
NodeList nodes = doc.getElementsByTagNameNS("*", "*");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
String nodeName = node.getNodeName();
if (nodeName != null && nodeName.equals("yt:videoid")) {
return node.getFirstChild().getNodeValue();
}
}
return null;
}
private static File getFileFromUri(Uri uri, Activity activity) {
try {
String filePath = null;
String[] proj = { Video.VideoColumns.DATA };
Cursor cursor = activity.getContentResolver().query(uri, proj, null, null, null);
if(cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(Video.VideoColumns.DATA);
filePath = cursor.getString(column_index);
}
cursor.close();
//String filePath = cursor.getString(cursor.getColumnIndex(Video.VideoColumns.DATA));
File file = new File(filePath);
cursor.close();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String uploadMetaData(YoutubeUploadRequest uploadRequest, String clientLoginToken, Activity activity, boolean retry) {
try {
File file = getFileFromUri(uploadRequest.getUri(), activity);
if(file != null) {
String uploadUrl = INITIAL_UPLOAD_URL;
URL url = new URL(uploadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", String.format("GoogleLogin auth=\"%s\"", clientLoginToken));
connection.setRequestProperty("GData-Version", "2");
connection.setRequestProperty("X-GData-Client", CLIENT_ID);
connection.setRequestProperty("X-GData-Key", String.format("key=%s", DEVELOPER_KEY));
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/atom+xml");
connection.setRequestProperty("Slug", file.getAbsolutePath());
String title = uploadRequest.getTitle();
String description = uploadRequest.getDescription();
String category = uploadRequest.getCategory();
String tags = uploadRequest.getTags();
String template = readFile(activity, R.raw.gdata).toString();
String atomData = String.format(template, title, description, category, tags);
/*String template = readFile(activity, R.raw.gdata_geo).toString();
atomData = String.format(template, title, description, category, tags,
videoLocation.getLatitude(), videoLocation.getLongitude());*/
OutputStreamWriter outStreamWriter = new OutputStreamWriter(connection.getOutputStream());
outStreamWriter.write(atomData);
outStreamWriter.close();
int responseCode = connection.getResponseCode();
if (responseCode < 200 || responseCode >= 300) {
// The response code is 40X
if ((responseCode + "").startsWith("4") && retry) {
Log.d(TAG, "retrying to fetch auth token for ");
clientLoginToken = getClientAuthToken();
// Try again with fresh token
return uploadMetaData(uploadRequest, clientLoginToken, activity, false);
} else {
return null;
}
}
return connection.getHeaderField("Location");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static CharSequence readFile(Activity activity, int id) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) {
buffer.append(line).append('\n');
}
// Chomp the last newline
buffer.deleteCharAt(buffer.length() - 1);
return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
/**
* Closes the specified stream.
*
* #param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
public static interface ProgressListner {
void onUploadProgressUpdate(int progress);
}
}
And here is YoutubeUploadRequest.java
import android.net.Uri;
public class YoutubeUploadRequest {
private static final String DEFAULT_VIDEO_CATEGORY = "News";
private static final String DEFAULT_VIDEO_TAGS = "mobile";
private String title;
private String strUri;
private String description;
private String category = DEFAULT_VIDEO_CATEGORY;
private String tags = DEFAULT_VIDEO_TAGS;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getStrUri() {
return strUri;
}
public void setStrUri(String strUri) {
this.strUri = strUri;
}
public Uri getUri() {
return Uri.parse(strUri);
}
public void setUri(Uri uri) {
this.strUri = uri.toString();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Also you will need raw/gdata.xml
<?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <media:group> <media:title type="plain">%s</media:title> <media:description type="plain">%s</media:description> <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">%s</media:category> <media:keywords>%s</media:keywords> </media:group> </entry>
Here is sample activity to use it : MainActivity.java
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.trialanderror.YoutubeUploader.ProgressListner;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static final int CAPTURE_RETURN = 1;
private static final int GALLERY_RETURN = 2;
private static final int SUBMIT_RETURN = 3;
private ProgressBar progressBar;
private Button btnCaptureVideo;
private Button btnSelectFromGallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCaptureVideo = (Button) findViewById(R.id.btnCaptureVideo);
btnCaptureVideo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction("android.media.action.VIDEO_CAPTURE");
startActivityForResult(i, CAPTURE_RETURN);
}
});
btnSelectFromGallery = (Button) findViewById(R.id.btnSelectFromGallery);
btnSelectFromGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("video/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() <= 0) {
Log.d(TAG, "no video picker intent on this hardware");
return;
}
startActivityForResult(intent, GALLERY_RETURN);
}
});
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
btnSelectFromGallery.setEnabled(true);
btnCaptureVideo.setEnabled(true);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CAPTURE_RETURN:
case GALLERY_RETURN:
if (resultCode == RESULT_OK) {
/*Intent intent = new Intent(this, SubmitActivity.class);
intent.setData(data.getData());
startActivityForResult(intent, SUBMIT_RETURN);*/
progressBar.setVisibility(View.VISIBLE);
btnSelectFromGallery.setEnabled(false);
btnCaptureVideo.setEnabled(false);
uploadYoutube(data.getData());
}
break;
case SUBMIT_RETURN:
if (resultCode == RESULT_OK) {
Toast.makeText(MainActivity.this, "thank you!", Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(DetailsActivity.this, "submit failed or cancelled",
// Toast.LENGTH_LONG).show();
}
break;
}
}
private void uploadYoutube(final Uri data) {
new AsyncTask<Void, Integer, Void>() {
#Override
protected Void doInBackground(Void... params) {
YoutubeUploadRequest request = new YoutubeUploadRequest();
request.setUri(data);
//request.setCategory(category);
//request.setTags(tags);
request.setTitle("MPRJ Video Tite");
request.setDescription("MPRJ Video Test");
YoutubeUploader.upload(request, new ProgressListner() {
#Override
public void onUploadProgressUpdate(int progress) {
publishProgress(progress);
}
}, MainActivity.this);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
if(values[0] == 100){
progressBar.setVisibility(View.GONE);
btnSelectFromGallery.setEnabled(true);
btnCaptureVideo.setEnabled(true);
}
};
}.execute();
}
}
Layout for sample activity activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="#string/upload_video" />
<Button
android:id="#+id/btnCaptureVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/capture_video" />
<Button
android:id="#+id/btnSelectFromGallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="#string/select_from_gallery" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_marginTop="15dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I have uploaded youtube video successfully.
Record video and upload
Videos from sdcard
by using this
steps:
1) Download ytd-android-0.2.tar.gz from this link
2) Import as an android project.
3) Replace file: GlsAuthorizer.java with ClientLoginAuthorizer.java
4) Set Username and password in ClientLoginAuthorizer.java
5) Register your email id with www.appspot.com
6) Set all values in string.xml file
7) Run project..... here you go.
code for ClientLoginAuthorizer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
/**
* Created by IntelliJ IDEA. User: jarekw Date: Nov 18, 2010 Time: 11:21:36 PM
* To change this template use File | Settings | File Templates.
*/
public class ClientLoginAuthorizer implements Authorizer {
public static final String YOUTUBE_AUTH_TOKEN_TYPE = "youtube";
private static final String AUTH_URL = "https://www.google.com/accounts/ClientLogin";
private Context ctx;
private static final String LOG_TAG = ClientLoginAuthorizer.class
.getSimpleName();
public ClientLoginAuthorizer(Context context) {
this.ctx = context;
}
#Override
public void fetchAccounts(AuthorizationListener<String[]> listener) {
// not used
}
#Override
public void addAccount(Activity activity,
AuthorizationListener<String> listener) {
// not used
}
#Override
public void fetchAuthToken(String accountName, Activity activity,
AuthorizationListener<String> listener) {
Log.d(LOG_TAG, "Getting " + YOUTUBE_AUTH_TOKEN_TYPE + " authToken for "
+ accountName);
try {
String token = getCLAuthToken(accountName);
listener.onSuccess(token);
} catch (Exception e) {
listener.onError(e);
}
}
#Override
public String getAuthToken(String accountName) {
try {
String token = getCLAuthToken(accountName);
return token;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public String getCLAuthToken(String accountName) throws IOException {
HttpURLConnection urlConnection = getGDataUrlConnection(AUTH_URL);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
String template = "Email=%s&Passwd=%s&service=%s&source=%s";
String userName = "USERNAME"; // TODO
String password = "PASSWORD"; // TODO
String service = YOUTUBE_AUTH_TOKEN_TYPE;
String source = ctx.getString(R.string.client_id);
String loginData = String.format(template, encode(userName),
encode(password), service, source);
OutputStreamWriter outStreamWriter = new OutputStreamWriter(
urlConnection.getOutputStream());
outStreamWriter.write(loginData);
outStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode != 200) {
Log.d(LOG_TAG, "Got an error response : " + responseCode + " "
+ urlConnection.getResponseMessage());
throw new IOException(urlConnection.getResponseMessage());
} else {
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("Auth=")) {
String split[] = line.split("=");
String token = split[1];
Log.d(LOG_TAG, "Auth Token : " + token);
return token;
}
}
}
throw new IOException("Could not read response");
}
private String encode(String string) throws UnsupportedEncodingException {
return URLEncoder.encode(string, "UTF-8");
}
private HttpURLConnection getGDataUrlConnection(String urlString)
throws IOException {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
return connection;
}
#Override
public String getFreshAuthToken(String accountName, String authToken) {
return getAuthToken(accountName);
}
public static class ClientLoginAuthorizerFactory implements
AuthorizerFactory {
public Authorizer getAuthorizer(Context context, String authTokenType) {
return new ClientLoginAuthorizer(context);
}
}
}
I have the below method:
public String tryGoogleAuthentication(String auth_token){
ContactsService contactsService = new ContactsService(".....");
contactsService.setUserToken(auth_token);
IFeed feed = null;
try {
feed = contactsService.getFeed(new URL("https://www.google.com/m8/feeds/ contacts/default/full?max-results=10000"), ContactFeed.class);
} catch (IOException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (ServiceException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (NullPointerException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
}
if (feed == null)
return "";
String externalId = feed.getId();
IPerson person = feed.getAuthors().get(0);
String email = person.getEmail();
String name = person.getName();
String nameLang = person.getNameLang();
System.out.println("externalId: " + externalId);
System.out.println("email: " + email);
System.out.println("name: " + name);
System.out.println("nameLang: " + nameLang);
return CONST.STATUS_OK;
}
and I get the error:
java.lang.NullPointerException: No authentication header information
at com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96)
at com.google.gdata.util.AuthenticationException.<init>(AuthenticationException.java:67)
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:600)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:998)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:631)
at com.google.gdata.client.Service.getFeed(Service.java:1017)
at ro.servlet.data.ClientAuthenticator.tryGoogleAuthentication(ClientAuthenticator.java:96)
....
Please tell what shoud I set to contactsService(except setUserToken) in order to work proper?
I don't used gData before(I'm an android/iPhone developer) - I took the auth string from the android device(by letting the user to confirm this) and pass it over a secured channel to my server - now I want to gather some data about this Contact(first, last name and provider uid - I need for a database with users in my app).
I really need to finish this task, so please, if anyone knows how this can be fixed, help me !
The below class describe the way I get the auth string from the android device.
package ro.locationsApp.android.login;
import java.io.IOException;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import ro.locationsApp.android.CONST;
import android.R;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class AccountList extends ListActivity {
protected AccountManager accountManager;
protected Intent intent;
DefaultHttpClient http_client = getThreadSafeClient();
private Account currentUsedAccount;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accountManager = AccountManager.get(getApplicationContext());
Account[] accounts = accountManager.getAccountsByType("com.google");
String[] names = new String[accounts.length];
for (int i = 0; i < accounts.length; i++) {
System.out.println(accounts[i].name);
names[i] = accounts[i].name;
}
this.setListAdapter(new ArrayAdapter<String>(this,
R.layout.simple_list_item_1, names));
}
#SuppressWarnings("unchecked")
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Account account = accountManager.getAccountsByType("com.google")[position];
accountManager.getAuthToken(account, "ah", false,
new GetAuthTokenCallback(), null);
currentUsedAccount = account;
}
public static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
#SuppressWarnings("rawtypes")
private class GetAuthTokenCallback implements AccountManagerCallback {
public void run(AccountManagerFuture result) {
Bundle bundle;
try {
bundle = (Bundle) result.getResult();
Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (intent != null) {
// User input required
startActivity(intent);
} else {
onGetAuthToken(bundle);
}
} 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();
}
}
};
protected void onGetAuthToken(Bundle bundle) {
final String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
System.out.println("AUTH TOKEN: " + auth_token);
new Thread(new Runnable() {
#Override
public void run() {
try {
JSONObject request = new JSONObject();
request.put(CONST.ID_ATTR, CONST.ID_GOOGLE_AUTH);
JSONObject body = new JSONObject();
body.put(CONST.GOOGLE_AUTH_TOKEN, auth_token);
request.put(CONST.DATA_ATTR, body);
JSONObject response = new JSONObject(new RequestHandler().request(DataSource.LOCATIONS_SERVER_URL, request.toString()));
String bodyResponse = response.optJSONObject(CONST.DATA_ATTR).optString(CONST.STATUS_ATTR);
if(bodyResponse.equals(CONST.STATUS_OK)){
}
else if(bodyResponse.equals(CONST.GOOGLE_AUTH_INVALID_TOKEN)){
runOnUiThread(new Runnable() {
#SuppressWarnings("unchecked")
public void run() {
invalidateUserToken(auth_token);
accountManager.getAuthToken(currentUsedAccount, "ah", false,
new GetAuthTokenCallback(), null);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public void invalidateUserToken(String token){
AccountManager accountManager = AccountManager.get(this);
accountManager.invalidateAuthToken("com.google", token);
}
}
Thanks,
Alex.
accountManager.getAuthToken(currentUsedAccount, "ah", false,
new GetAuthTokenCallback(), null);
Your accountTokenType is wrong. The Contacts API scope is http://www.google.com/m8/feeds/ for v2 or https://www.google.com/m8/feeds/ for v3