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 {
}
}
}
Related
I am Successful intrigate PayUMoney Payment Gateway In My App. I want to call one class or Activity if Successfully Payment Done. And if Payment Was Failed This class or Activity Does not Call. I was trying lot of things but nothing is work for me.
PayUMoneyActivity.java
package com.payumoneywebviewintri;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
#SuppressLint("SetJavaScriptEnabled")
public class PayUMoneyActivity extends AppCompatActivity {
String merchant_key = "OygoFs";
String salt = "BV1QBwCv";
String action1 = "";
String base_url = "https://test.payu.in";
// int error = 0;
// String hashString = "";
// Map<String, String> params;
String txnid = "";
String amount = "1";
String productInfo = "";
String firstName = "Basit";
String emailId = "abdulbasitkhan88#gmail.com";
private String SUCCESS_URL = "http://er.16mb.com/success.php";
private String FAILED_URL = "http://er.16mb.com/failure.php";
private String phone = "7817857472";
private String serviceProvider = "payu_paisa";
private String hash = "";
Handler mHandler = new Handler();
private WebView webView;
#SuppressLint("JavascriptInterface")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_umoney);
// getWindow().requestFeature(Window.FEATURE_PROGRESS);
// webView = new WebView(this);
// setContentView(webView);
webView = (WebView)findViewById(R.id.wb);
JSONObject productInfoObj = new JSONObject();
JSONArray productPartsArr = new JSONArray();
JSONObject productPartsObj1 = new JSONObject();
JSONObject paymentIdenfierParent = new JSONObject();
JSONArray paymentIdentifiersArr = new JSONArray();
JSONObject paymentPartsObj1 = new JSONObject();
JSONObject paymentPartsObj2 = new JSONObject();
try {
// Payment Parts
productPartsObj1.put("name", "abc");
productPartsObj1.put("description", "abcd");
productPartsObj1.put("value", "1");
productPartsObj1.put("isRequired", "true");
productPartsObj1.put("settlementEvent", "EmailConfirmation");
productPartsArr.put(productPartsObj1);
productInfoObj.put("paymentParts", productPartsArr);
// Payment Identifiers
paymentPartsObj1.put("field", "CompletionDate");
paymentPartsObj1.put("value", "05/08/2016");
paymentIdentifiersArr.put(paymentPartsObj1);
paymentPartsObj2.put("field", "TxnId");
paymentPartsObj2.put("value", txnid);
paymentIdentifiersArr.put(paymentPartsObj2);
paymentIdenfierParent.put("paymentIdentifiers",
paymentIdentifiersArr);
productInfoObj.put("", paymentIdenfierParent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
productInfo = productInfoObj.toString();
Log.e("TAG", productInfoObj.toString());
Random rand = new Random();
String rndm = Integer.toString(rand.nextInt())
+ (System.currentTimeMillis() / 1000L);
txnid = hashCal("SHA-256", rndm).substring(0, 20);
hash = hashCal("SHA-512", merchant_key + "|" + txnid + "|" + amount
+ "|" + productInfo + "|" + firstName + "|" + emailId
+ "|||||||||||" + salt);
action1 = base_url.concat("/_payment");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
Toast.makeText(PayUMoneyActivity.this, "Oh no! " + description,
Toast.LENGTH_LONG).show();
}
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
// TODO Auto-generated method stub
Toast.makeText(PayUMoneyActivity.this, "SslError! " + error,
Toast.LENGTH_LONG).show();
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Toast.makeText(PayUMoneyActivity.this, "Page Started! " + url,
Toast.LENGTH_LONG).show();
if (url.equals(SUCCESS_URL)) {
Intent i = new Intent(PayUMoneyActivity.this,TestActivity.class);
startActivity(i);
Toast.makeText(PayUMoneyActivity.this, "Success! " + url,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(PayUMoneyActivity.this, "Failure! " + url,
Toast.LENGTH_LONG).show();
}
return super.shouldOverrideUrlLoading(view, url);
}
//
// #Override
// public void onPageFinished(WebView view, String url) {
// super.onPageFinished(view, url);
//
// Toast.makeText(PayMentGateWay.this, "" + url,
// Toast.LENGTH_SHORT).show();
// }
});
webView.setVisibility(View.VISIBLE);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setCacheMode(2);
webView.getSettings().setDomStorageEnabled(true);
webView.clearHistory();
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUseWideViewPort(false);
webView.getSettings().setLoadWithOverviewMode(true);
webView.addJavascriptInterface(new PayUJavaScriptInterface(PayUMoneyActivity.this),
"PayUMoney");
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("key", merchant_key);
mapParams.put("hash", hash);
mapParams.put("txnid", txnid);
mapParams.put("service_provider", "payu_paisa");
mapParams.put("amount", amount);
mapParams.put("firstname", firstName);
mapParams.put("email", emailId);
mapParams.put("phone", phone);
mapParams.put("productinfo", productInfo);
mapParams.put("surl", SUCCESS_URL);
mapParams.put("furl", FAILED_URL);
mapParams.put("lastname", "");
mapParams.put("address1", "");
mapParams.put("address2", "");
mapParams.put("city", "");
mapParams.put("state", "");
mapParams.put("country", "");
mapParams.put("zipcode", "");
mapParams.put("udf1", "");
mapParams.put("udf2", "");
mapParams.put("udf3", "");
mapParams.put("udf4", "");
mapParams.put("udf5", "");
// mapParams.put("pg", (empty(PayMentGateWay.this.params.get("pg"))) ?
// ""
// : PayMentGateWay.this.params.get("pg"));
webview_ClientPost(webView, action1, mapParams.entrySet());
}
public class PayUJavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
PayUJavaScriptInterface(Context c) {
mContext = c;
}
public void success(long id, final String paymentId) {
mHandler.post(new Runnable() {
public void run() {
mHandler = null;
// Toast.makeText(PayMentGateWay.this, "Success",
// Toast.LENGTH_SHORT).show();
}
});
}
}
public void webview_ClientPost(WebView webView, String url,
Collection<Map.Entry<String, String>> postData) {
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head>");
sb.append("<body onload='form1.submit()'>");
sb.append(String.format("<form id='form1' action='%s' method='%s'>",
url, "post"));
for (Map.Entry<String, String> item : postData) {
sb.append(String.format(
"<input name='%s' type='hidden' value='%s' />",
item.getKey(), item.getValue()));
}
sb.append("</form></body></html>");
// Log.d(tag, "webview_ClientPost called");
webView.loadData(sb.toString(), "text/html", "utf-8");
}
public boolean empty(String s) {
if (s == null || s.trim().equals(""))
return true;
else
return false;
}
public String hashCal(String type, String str) {
byte[] hashseq = str.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashseq);
byte messageDigest[] = algorithm.digest();
for (int i = 0; i < messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
if (hex.length() == 1)
hexString.append("0");
hexString.append(hex);
}
} catch (NoSuchAlgorithmException nsae) {
}
return hexString.toString();
}
}
webviewPayment.getSettings().setJavaScriptEnabled(true);
webviewPayment.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webviewPayment, url);
if (dialog.isShowing())
dialog.dismiss();
if(url.equals(SUCCESS_URL))
{
if (cd.isConnectingToInternet()) {
new GetBookSeatOperation().execute();
}
else {
Toaster.make(getActivity(), R.string.err_went_wrong );
} }
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getActivity(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
// }
} else {
Toaster.make(getActivity(), R.string.err_went_wrong);
}
Maybe I misunderstood, but you could simply use
mContext.startActivity(new Intent(mContext, YourActivity.class);
I have been uploading video directly to youtube using API where i can take authToken for default accounts which has already linked with their device. Now i want to take authtoken for static username and password of youtube to do so.
i have done by using code of Vaibhav A. Jani thanks to him. but i got issue like java.io.IOException: Not Found While getting ClientAuthToken.
How to Resolve this issues ? or any other example and api to do
Thanks in Advance.
My Code Part 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;
}
}
Here is My 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();
}
}
hey guys so i have aa working oAuth application and everything is fine up until the point at which the application tries o fetch the user information and it fails could i have some guidance on how to fix this? thank you
InstagramApp.java
package br.com.dina.oauth.instagram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import br.com.dina.oauth.instagram.InstagramDialog.OAuthDialogListener;
public class InstagramApp {
private InstagramSession mSession;
private InstagramDialog mDialog;
private OAuthAuthenticationListener mListener;
private ProgressDialog mProgress;
private String mAuthUrl;
private String mTokenUrl;
private String mAccessToken;
private Context mCtx;
private String mClientId;
private String mClientSecret;
private static int WHAT_FINALIZE = 0;
private static int WHAT_ERROR = 1;
private static int WHAT_FETCH_INFO = 2;
/**
* Callback url, as set in 'Manage OAuth Costumers' page
* (https://developer.github.com/)
*/
public static String mCallbackUrl = "";
private static final String AUTH_URL = "https://api.instagram.com/oauth/authorize/";
private static final String TOKEN_URL = "https://api.instagram.com/oauth/access_token";
private static final String API_URL = "https://api.instagram.com/v1/users/21846697/media/recent/";
private static final String TAG = "InstagramAPI";
public InstagramApp(Context context, String clientId, String clientSecret,
String callbackUrl) {
mClientId = clientId;
mClientSecret = clientSecret;
mCtx = context;
mSession = new InstagramSession(context);
mAccessToken = mSession.getAccessToken();
mCallbackUrl = callbackUrl;
mTokenUrl = TOKEN_URL + "?client_id=" + clientId + "&client_secret="
+ clientSecret + "&redirect_uri=" + mCallbackUrl + "&grant_type=authorization_code";
mAuthUrl = AUTH_URL + "?client_id=" + clientId + "&redirect_uri="
+ mCallbackUrl + "&response_type=code&display=touch&scope=likes+comments+relationships";
OAuthDialogListener listener = new OAuthDialogListener() {
#Override
public void onComplete(String code) {
getAccessToken(code);
}
#Override
public void onError(String error) {
mListener.onFail("Authorization failed");
}
};
mDialog = new InstagramDialog(context, mAuthUrl, listener);
mProgress = new ProgressDialog(context);
mProgress.setCancelable(false);
}
private void getAccessToken(final String code) {
mProgress.setMessage("Getting access token ...");
mProgress.show();
new Thread() {
#Override
public void run() {
Log.i(TAG, "Getting access token");
int what = WHAT_FETCH_INFO;
try {
URL url = new URL(TOKEN_URL);
//URL url = new URL(mTokenUrl + "&code=" + code);
Log.i(TAG, "Opening Token URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
//urlConnection.connect();
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write("client_id="+mClientId+
"&client_secret="+mClientSecret+
"&grant_type=authorization_code" +
"&redirect_uri="+mCallbackUrl+
"&code=" + code);
writer.flush();
String response = streamToString(urlConnection.getInputStream());
Log.i(TAG, "response " + response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
mAccessToken = jsonObj.getString("access_token");
Log.i(TAG, "Got access token: " + mAccessToken);
String id = jsonObj.getJSONObject("user").getString("id");
String user = jsonObj.getJSONObject("user").getString("username");
String name = jsonObj.getJSONObject("user").getString("full_name");
mSession.storeAccessToken(mAccessToken, id, user, name);
} catch (Exception ex) {
what = WHAT_ERROR;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0));
}
}.start();
}
private void fetchUserName() {
mProgress.setMessage("Finalizing ...");
new Thread() {
#Override
public void run() {
Log.i(TAG, "Fetching user info");
int what = WHAT_FINALIZE;
try {
URL url = new URL(API_URL + "/users/" + mSession.getId() + "/?access_token=" + mAccessToken);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio = jsonObj.getJSONObject("data").getString("bio");
Log.i(TAG, "Got name: " + name + ", bio [" + bio + "]");
} catch (Exception ex) {
what = WHAT_ERROR;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == WHAT_ERROR) {
mProgress.dismiss();
if(msg.arg1 == 1) {
mListener.onFail("Failed to get access token");
}
else if(msg.arg1 == 2) {
mListener.onFail("Failed to get user information");
}
}
else if(msg.what == WHAT_FETCH_INFO) {
fetchUserName();
}
else {
mProgress.dismiss();
mListener.onSuccess();
}
}
};
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void setListener(OAuthAuthenticationListener listener) {
mListener = listener;
}
public String getUserName() {
return mSession.getUsername();
}
public String getId() {
return mSession.getId();
}
public String getName() {
return mSession.getName();
}
public void authorize() {
//Intent webAuthIntent = new Intent(Intent.ACTION_VIEW);
//webAuthIntent.setData(Uri.parse(AUTH_URL));
//mCtx.startActivity(webAuthIntent);
mDialog.show();
}
private String streamToString(InputStream is) throws IOException {
String str = "";
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} finally {
is.close();
}
str = sb.toString();
}
return str;
}
public void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public interface OAuthAuthenticationListener {
public abstract void onSuccess();
public abstract void onFail(String error);
}
}
ApplicationData.java
package br.com.dina.oauth.instagram.example;
public class ApplicationData {
public static final String CLIENT_ID = "My Personal ID";
public static final String CLIENT_SECRET = "My Personal Secret";
public static final String CALLBACK_URL = "http://www.yahoo.com";
}
I'm trying to fetch user data from Instagram in a Android application, because I need to get user photos and show in a gallery, but I'm having a problem to fetch user data.
Here is the code:
private void fetchUserName() {
mProgress.setMessage("Finalizing ...");
new Thread() {
#Override
public void run() {
Log.i(TAG, "Fetching user info");
int what = WHAT_FINALIZE;
try {
URL url = new URL(API_URL + "/users/" + mSession.getId() + "/media/recent/?access_token=" + mAccessToken);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio = jsonObj.getJSONObject("data").getString("bio");
Log.i(TAG, "Got name: " + name + ", bio [" + bio + "]");
} catch (Exception ex) {
what = WHAT_ERROR;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
But in this part is going to catch.
String response = streamToString(urlConnection.getInputStream());
And I tried many ways to do JSON parse, but always give error when try to connect to url, like it:
HttpResponse httpResponse = httpClient.execute(httpPost);
The url logged is :
https://api.instagram.com/v1/users/699022341/?access_token=699022341.aef690f.1888e66fed5d4764aeae1c121faa14fb
And the error is:
11-29 14:31:45.300: W/System.err(11916): java.io.FileNotFoundException: https://api.instagram.com/v1/users/699022341/?access_token=699022341.aef690f.1888e66fed5d4764aeae1c121faa14fb
11-29 14:31:45.300: W/System.err(11916): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
11-29 14:31:45.300: W/System.err(11916): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
I'm doing something wrong or need a Instagram permission, or something like that?
I used the below code for Instagram user authentication process, here is share my code. Hope it will help to you,
InstagramApp.java
package br.com.dina.oauth.instagram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import br.com.dina.oauth.instagram.InstagramDialog.OAuthDialogListener;
/**
*
* #author Thiago Locatelli <thiago.locatelli#gmail.com>
* #author Lorensius W. L T <lorenz#londatiga.net>
*
*/
public class InstagramApp {
private InstagramSession mSession;
private InstagramDialog mDialog;
private OAuthAuthenticationListener mListener;
private ProgressDialog mProgress;
private String mAuthUrl;
private String mTokenUrl;
private String mAccessToken;
private Context mCtx;
private String mClientId;
private String mClientSecret;
private static int WHAT_FINALIZE = 0;
private static int WHAT_ERROR = 1;
private static int WHAT_FETCH_INFO = 2;
/**
* Callback url, as set in 'Manage OAuth Costumers' page
* (https://developer.github.com/)
*/
public static String mCallbackUrl = "";
private static final String AUTH_URL = "https://api.instagram.com/oauth/authorize/";
private static final String TOKEN_URL = "https://api.instagram.com/oauth/access_token";
private static final String API_URL = "https://api.instagram.com/v1";
private static final String TAG = "InstagramAPI";
public InstagramApp(Context context, String clientId, String clientSecret,
String callbackUrl) {
mClientId = clientId;
mClientSecret = clientSecret;
mCtx = context;
mSession = new InstagramSession(context);
mAccessToken = mSession.getAccessToken();
mCallbackUrl = callbackUrl;
mTokenUrl = TOKEN_URL + "?client_id=" + clientId + "&client_secret="
+ clientSecret + "&redirect_uri=" + mCallbackUrl
+ "&grant_type=authorization_code";
mAuthUrl = AUTH_URL
+ "?client_id="
+ clientId
+ "&redirect_uri="
+ mCallbackUrl
+ "&response_type=code&display=touch&scope=likes+comments+relationships";
OAuthDialogListener listener = new OAuthDialogListener() {
#Override
public void onComplete(String code) {
getAccessToken(code);
}
#Override
public void onError(String error) {
mListener.onFail("Authorization failed");
}
};
mDialog = new InstagramDialog(context, mAuthUrl, listener);
mProgress = new ProgressDialog(context);
mProgress.setCancelable(false);
}
private void getAccessToken(final String code) {
mProgress.setMessage("Getting access token ...");
mProgress.show();
new Thread() {
#Override
public void run() {
Log.i(TAG, "Getting access token");
int what = WHAT_FETCH_INFO;
try {
URL url = new URL(TOKEN_URL);
// URL url = new URL(mTokenUrl + "&code=" + code);
Log.i(TAG, "Opening Token URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
// urlConnection.connect();
OutputStreamWriter writer = new OutputStreamWriter(
urlConnection.getOutputStream());
writer.write("client_id=" + mClientId + "&client_secret="
+ mClientSecret + "&grant_type=authorization_code"
+ "&redirect_uri=" + mCallbackUrl + "&code=" + code);
writer.flush();
String response = streamToString(urlConnection
.getInputStream());
Log.i(TAG, "response " + response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response)
.nextValue();
mAccessToken = jsonObj.getString("access_token");
// Log.i(TAG, "Got access token: " + mAccessToken);
String id = jsonObj.getJSONObject("user").getString("id");
String user = jsonObj.getJSONObject("user").getString(
"username");
String name = jsonObj.getJSONObject("user").getString(
"full_name");
String userImage = jsonObj.getJSONObject("user").getString(
"profile_picture");
mSession.storeAccessToken(mAccessToken, id, user, name,
userImage);
} catch (Exception ex) {
what = WHAT_ERROR;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0));
}
}.start();
}
private void fetchUserName() {
mProgress.setMessage("Finalizing ...");
new Thread() {
#Override
public void run() {
Log.i(TAG, "Fetching user info");
int what = WHAT_FINALIZE;
try {
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response)
.nextValue();
String name = jsonObj.getJSONObject("data").getString(
"full_name");
// String bio =
// jsonObj.getJSONObject("data").getString("bio");
Log.i(TAG, "Got name: " + name);
} catch (Exception ex) {
what = WHAT_ERROR;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == WHAT_ERROR) {
mProgress.dismiss();
if (msg.arg1 == 1) {
mListener.onFail("Failed to get access token");
} else if (msg.arg1 == 2) {
mListener.onFail("Failed to get user information");
}
} else if (msg.what == WHAT_FETCH_INFO) {
mProgress.dismiss();
mListener.onSuccess();
// fetchUserName();
} else {
// mProgress.dismiss();
// mListener.onSuccess();
}
}
};
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void setListener(OAuthAuthenticationListener listener) {
mListener = listener;
}
// getting username
public String getUserName() {
return mSession.getUsername();
}
// getting user id
public String getId() {
return mSession.getId();
}
// getting username
public String getName() {
return mSession.getName();
}
// getting user image
public String getUserPicture() {
return mSession.getUserImage();
}
// getting accesstoken
public String getAccessToken() {
return mSession.getAccessToken();
}
public void authorize() {
// Intent webAuthIntent = new Intent(Intent.ACTION_VIEW);
// webAuthIntent.setData(Uri.parse(AUTH_URL));
// mCtx.startActivity(webAuthIntent);
mDialog.show();
}
private String streamToString(InputStream is) throws IOException {
String str = "";
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} finally {
is.close();
}
str = sb.toString();
}
return str;
}
public void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public interface OAuthAuthenticationListener {
public abstract void onSuccess();
public abstract void onFail(String error);
}
}
InstagramDialog.java
package br.com.dina.oauth.instagram;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Display 37Signals authentication dialog.
*
* #author Thiago Locatelli <thiago.locatelli#gmail.com>
* #author Lorensius W. L T <lorenz#londatiga.net>
*
*/
public class InstagramDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = { 460, 260 };
static final float[] DIMENSIONS_PORTRAIT = { 420, 420 };
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private OAuthDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Instagram-WebView";
public InstagramDialog(Context context, String url,
OAuthDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT
: DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams(
(int) (dimensions[0] * scale + 0.5f), (int) (dimensions[1]
* scale + 0.5f)));
CookieSyncManager.createInstance(getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
mTitle = new TextView(getContext());
mTitle.setText("Instagram");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(Color.BLACK);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new OAuthWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class OAuthWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(InstagramApp.mCallbackUrl)) {
String urls[] = url.split("=");
mListener.onComplete(urls[1]);
InstagramDialog.this.dismiss();
return true;
}
return false;
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
InstagramDialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
Log.d(TAG, "onPageFinished URL: " + url);
mSpinner.dismiss();
}
}
public interface OAuthDialogListener {
public abstract void onComplete(String accessToken);
public abstract void onError(String error);
}
}
InstagramSession.java
package br.com.dina.oauth.instagram;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* Manage access token and user name. Uses shared preferences to store access
* token and user name.
*
* #author Thiago Locatelli <thiago.locatelli#gmail.com>
* #author Lorensius W. L T <lorenz#londatiga.net>
*
*/
public class InstagramSession {
private SharedPreferences sharedPref;
private Editor editor;
private static final String SHARED = "Instagram_Preferences";
private static final String API_USERNAME = "username";
private static final String API_ID = "id";
private static final String API_NAME = "name";
private static final String API_ACCESS_TOKEN = "access_token";
private static final String API_USER_IMAGE = "user_image";
public InstagramSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
/**
*
* #param accessToken
* #param expireToken
* #param expiresIn
* #param username
*/
public void storeAccessToken(String accessToken, String id,
String username, String name, String image) {
editor.putString(API_ID, id);
editor.putString(API_NAME, name);
editor.putString(API_ACCESS_TOKEN, accessToken);
editor.putString(API_USERNAME, username);
editor.putString(API_USER_IMAGE, image);
editor.commit();
}
public void storeAccessToken(String accessToken) {
editor.putString(API_ACCESS_TOKEN, accessToken);
editor.commit();
}
/**
* Reset access token and user name
*/
public void resetAccessToken() {
editor.putString(API_ID, null);
editor.putString(API_NAME, null);
editor.putString(API_ACCESS_TOKEN, null);
editor.putString(API_USERNAME, null);
editor.putString(API_USER_IMAGE, null);
editor.commit();
}
/**
* Get user name
*
* #return User name
*/
public String getUsername() {
return sharedPref.getString(API_USERNAME, null);
}
/**
*
* #return
*/
public String getId() {
return sharedPref.getString(API_ID, null);
}
/**
*
* #return
*/
public String getName() {
return sharedPref.getString(API_NAME, null);
}
/**
* Get access token
*
* #return Access token
*/
public String getAccessToken() {
return sharedPref.getString(API_ACCESS_TOKEN, null);
}
/**
* Get userImage
*
* #return userImage
*/
public String getUserImage() {
return sharedPref.getString(API_USER_IMAGE, null);
}
}
The above three classes are static one and i say my thanks to the author, in InstagramApp.java class i little bit modified the getter setter methods to get all user values, and in MainActivity.java i used the below code.
private InstagramApp instaObj;
public static final String CLIENT_ID = "Your_ID";
public static final String CLIENT_SECRET = "Your_Sec_Key";
public static final String CALLBACK_URL = "Your_call_back_URL";
// Instagram Implementation
instaObj = new InstagramApp(this, CLIENT_ID,
CLIENT_SECRET, CALLBACK_URL);
instaObj.setListener(listener);
instaObj.authorize(); //add this in your button click or wherever you need to call the instagram api
OAuthAuthenticationListener listener = new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
Log.e("Userid", instaObj.getId());
Log.e("Name", instaObj.getName());
Log.e("UserName", instaObj.getUserName());
}
#Override
public void onFail(String error) {
Toast.makeText(LoginPageActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
};
Your InstagramApp.java
Just replace it with your current class in library.
package br.com.dina.oauth.instagram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import br.com.dina.oauth.instagram.InstagramDialog.OAuthDialogListener;
/**
*
* #author Thiago Locatelli <thiago.locatelli#gmail.com>
* #author Lorensius W. L T <lorenz#londatiga.net>
*
*/
public class InstagramApp {
private InstagramSession mSession;
private InstagramDialog mDialog;
private OAuthAuthenticationListener mListener;
private ProgressDialog mProgress;
private String mAuthUrl;
private String mTokenUrl;
private String mAccessToken;
private Context mCtx;
private String mClientId;
private String mClientSecret;
private static int WHAT_FINALIZE = 0;
private static int WHAT_ERROR = 1;
private static int WHAT_FETCH_INFO = 2;
/**
* Callback url, as set in 'Manage OAuth Costumers' page
* (https://developer.github.com/)
*/
public static String mCallbackUrl = "";
private static final String AUTH_URL = "https://api.instagram.com/oauth/authorize/";
private static final String TOKEN_URL = "https://api.instagram.com/oauth/access_token";
private static final String API_URL = "https://api.instagram.com/v1";
private static final String TAG = "InstagramAPI";
public InstagramApp(Context context, String clientId, String clientSecret,
String callbackUrl) {
mClientId = clientId;
mClientSecret = clientSecret;
mCtx = context;
mSession = new InstagramSession(context);
mAccessToken = mSession.getAccessToken();
mCallbackUrl = callbackUrl;
mTokenUrl = TOKEN_URL + "?client_id=" + clientId + "&client_secret="
+ clientSecret + "&redirect_uri=" + mCallbackUrl + "&grant_type=authorization_code";
mAuthUrl = AUTH_URL + "?client_id=" + clientId + "&redirect_uri="
+ mCallbackUrl + "&response_type=code&display=touch&scope=likes+comments+relationships";
OAuthDialogListener listener = new OAuthDialogListener() {
#Override
public void onComplete(String code) {
getAccessToken(code);
}
#Override
public void onError(String error) {
mListener.onFail("Authorization failed");
}
};
mDialog = new InstagramDialog(context, mAuthUrl, listener);
mProgress = new ProgressDialog(context);
mProgress.setCancelable(false);
}
private void getAccessToken(final String code) {
mProgress.setMessage("Getting access token ...");
mProgress.show();
new Thread() {
#Override
public void run() {
Log.i(TAG, "Getting access token");
int what = WHAT_FETCH_INFO;
try {
URL url = new URL(TOKEN_URL);
//URL url = new URL(mTokenUrl + "&code=" + code);
Log.i(TAG, "Opening Token URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
//urlConnection.connect();
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write("client_id="+mClientId+
"&client_secret="+mClientSecret+
"&grant_type=authorization_code" +
"&redirect_uri="+mCallbackUrl+
"&code=" + code);
writer.flush();
String response = streamToString(urlConnection.getInputStream());
Log.i(TAG, "response " + response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
mAccessToken = jsonObj.getString("access_token");
Log.i(TAG, "Got access token: " + mAccessToken);
String id = jsonObj.getJSONObject("user").getString("id");
String user = jsonObj.getJSONObject("user").getString("username");
String name = jsonObj.getJSONObject("user").getString("full_name");
mSession.storeAccessToken(mAccessToken, id, user, name);
} catch (Exception ex) {
what = WHAT_ERROR;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0));
}
}.start();
}
private void fetchUserName() {
mProgress.setMessage("Finalizing ...");
new Thread() {
#Override
public void run() {
Log.i(TAG, "Fetching user info");
int what = WHAT_FINALIZE;
try {
URL url = new URL(API_URL + "/users/" + mSession.getId() + "/?access_token=" + mAccessToken);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
//urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio = jsonObj.getJSONObject("data").getString("bio");
Log.i(TAG, "Got name: " + name + ", bio [" + bio + "]");
} catch (Exception ex) {
what = WHAT_ERROR;
ex.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == WHAT_ERROR) {
mProgress.dismiss();
if(msg.arg1 == 1) {
mListener.onFail("Failed to get access token");
}
else if(msg.arg1 == 2) {
mListener.onFail("Failed to get user information");
}
}
else if(msg.what == WHAT_FETCH_INFO) {
fetchUserName();
}
else {
mProgress.dismiss();
mListener.onSuccess();
}
}
};
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public void setListener(OAuthAuthenticationListener listener) {
mListener = listener;
}
public String getUserName() {
return mSession.getUsername();
}
public String getId() {
return mSession.getId();
}
public String getName() {
return mSession.getName();
}
public void authorize() {
//Intent webAuthIntent = new Intent(Intent.ACTION_VIEW);
//webAuthIntent.setData(Uri.parse(AUTH_URL));
//mCtx.startActivity(webAuthIntent);
mDialog.show();
}
private String streamToString(InputStream is) throws IOException {
String str = "";
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} finally {
is.close();
}
str = sb.toString();
}
return str;
}
public void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public interface OAuthAuthenticationListener {
public abstract void onSuccess();
public abstract void onFail(String error);
}
}
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);
}
}
}