Android calls Youku SDK to upload videos. Android SDK

Source: Internet
Author: User

Android calls Youku SDK to upload videos. Android SDK
Recently, we are studying the function of using Youku SDK to upload videos. Because Youku SDK only provides a sample code for uploading and does not involve authorization, for new users, it may be tricky. Now let's share my thoughts:
Before the program implementation, we first to download the SDK Youku Open Platform (: http://open.youku.com/down) According to Youku SDK instructions, the upload process is mainly divided into the following 7 steps:

1. Create an android project and introduce the YoukuUploadSDK-android jar package

2. Add relevant parameters to the MainActivity. java file, as shown in sample. java.

3. Add the control in activity_main.xml under the folder layout.

4. generate code (xml file code)

5. Connect to the android phone and run the android project to generate the apk (remember to enable the developer option usb debugging, etc)

6. authorization process (get access_token)

7. Click upload.


The other steps follow the document and there should be no problem. Next we will focus on the authorization process in Step 6.

We can only use the general authorization method (the authorization method at the cooperation level needs to be charged). For details about the authorization mechanism, refer to http://open.youku.com/docs/oauth2.html.

The general idea is, through a WebView to display the authorization page to obtain the authorization code (code), we need to use the http method to get the authorization code (code), the required parameters please refer to the http://open.youku.com/docs/OAuth2.html? Id = 101, and then use the authorization code (code) to exchange the token, which is the so-called access_token. Finally, use the access_token to obtain the upload permission.

The Code is as follows:

AndroidManifest. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "com. youku. uploader "android: versionCode =" 1 "android: versionName =" 1.0 "> <uses-sdk android: minSdkVersion =" 11 "android: targetSdkVersion = "17"/> <uses-permission android: name = "android. permission. INTERNET "/> <uses-permission android: name =" android. permission. READ_EXTERNAL_STORAGE "/> <uses-permission android: name =" android. per Mission. WRITE_EXTERNAL_STORAGE "/> <uses-permission android: name =" android. permission. RECORD_AUDIO "/> <! -- This permission is used for network positioning --> <uses-permission android: name = "android. permission. ACCESS_COARSE_LOCATION"/> <! -- This permission is used to access GPS positioning --> <uses-permission android: name = "android. permission. ACCESS_FINE_LOCATION"/> <! -- Used to access Wi-Fi network information. wifi information is used to locate the network --> <uses-permission android: name = "android. permission. ACCESS_WIFI_STATE"/> <! -- Obtains carrier information, which is used to support interfaces related to carrier information --> <uses-permission android: name = "android. permission. ACCESS_NETWORK_STATE"/> <! -- This permission is used to obtain the permission for wifi, And wifi information is used to locate the network --> <uses-permission android: name = "android. permission. CHANGE_WIFI_STATE"/> <! -- Used to read the current status of the mobile phone --> <uses-permission android: name = "android. permission. READ_PHONE_STATE"/> <! -- Write extended storage and write data to the expansion card to write offline positioning data --> <uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/> <! -- SD card read permission, users write offline positioning data --> <uses-permission android: name = "android. permission. MOUNT_UNMOUNT_FILESYSTEMS "/> <application android: allowBackup =" true "android: icon =" @ drawable/ic_launcher "android: label =" @ string/app_name "android: theme = "@ style/AppTheme"> <activity android: name = "sample. getCodeActivity "android: label =" @ string/app_name "> <intent-filter> <action android: name =" android. intent. action. MAIN "/> <category android: name =" android. intent. category. LAUNCHER "/> </intent-filter> </activity> <activity android: name =" sample. mainActivity "android: label =" @ string/app_name "> </activity> </application> </manifest>
GetCodeActivity. java

Package sample; import java. util. arrayList; import java. util. list; import org. apache. http. httpResponse; import org. apache. http. nameValuePair; import org. apache. http. client. entity. urlEncodedFormEntity; import org. apache. http. client. methods. httpPost; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. message. basicNameValuePair; import org. apache. http. protocol. HTTP; import org. apache. h Ttp. util. entityUtils; import org. json. JSONObject; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. util. log; import android. webkit. webView; import android. webkit. webViewClient; import android. widget. toast; import com. youku. uploader. r; public class GetCodeActivity extends Activity {private WebView webview; private String strCode; private String access_toke N; private String CLIENT_ID = "38bae68624af4531"; private String CLIENT_SECRET = "secret"; private String TAG = "GetCodeActivity"; private String REDIRECT_URL = "https://client.example.com/cb "; @ Override protected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stub super. onCreate (savedInstanceState); setContentView (R. layout. request_code); // sets the Web View w Ebview = (WebView) findViewById (R. id. webView1); if (webview = null) {return ;} // below this link can be as long as the client_id and redirect_uri after the value of our application for Youku developer account Youku provided and we set the callback address can String url = "https://openapi.youku.com/v2/oauth2/authorize? Client_id = "+ CLIENT_ID +" & response_type = code & redirect_uri = "+ REDIRECT_URL +" & state = xyz "; webview. loadUrl (url); // A https://api.weibo.com/oauth2/default.html Log. d (TAG, "load before =" + url); webview. setWebViewClient (new WebViewClient () {@ Override public boolean shouldOverrideUrlLoading (WebView view, String url) {// TODO Auto-generated method stub view. loadUrl (url); String [] str = null; str = url. split ("= ") [1]. split ("&"); strCode = str [0]; Intent it = new Intent (); it. putExtra ("code", strCode); it. putExtra ("access_token", getToken (); Log. d (TAG, "code =" + strCode + "status =" + str [1] + "" + url + "token =" + getToken (); // Toast. makeText (getApplicationContext (), strCode, 0 ). show (); it. setClass (GetCodeActivity. this, MainActivity. class); startActivity (it); return false ;}});} private String getToken (){// TODO Auto-generated method stub Thread t = new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubString strUrl = "https://openapi.youku.com/v2/oauth2/token "; httpResponse httpResponse = null; HttpPost httpPost = new HttpPost (strUrl); List <NameValuePair> params = new ArrayList <NameValuePair> (); params. add (new BasicNameValuePair ("client_id", CLIENT_ID); // you apply for Youku's cl Ient_id params. add (new BasicNameValuePair ("client_secret", CLIENT_SECRET); // you apply for the client_secret params of Youku. add (new BasicNameValuePair ("grant_type", "authorization_code"); params. add (new BasicNameValuePair ("code", strCode); // code params obtained just now. add (new BasicNameValuePair ("redirect_uri", REDIRECT_URL); // The callback address, which must be the same as the website. try {httpPost. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); Log. d (TAG, "ge TToken () setEntity after "); httpResponse = new defaulthttpclient(.exe cute (httpPost); if (httpResponse. getStatusLine (). getStatusCode () == 200) {String result = EntityUtils. toString (httpResponse. getEntity (); Log. d (TAG, "result =" + result); System. out. println (result); JSONObject object = new JSONObject (result); access_token = object. getString ("access_token"); // access_token is obtained successfully // Toast. makeText (ge TApplicationContext (), "access_token =" + access_token, 0 ). show (); // return access_token;} else {Log. d (TAG, "getToken () getStatusCode =" + httpResponse. getStatusLine (). getStatusCode () ;}} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace (); Log. d (TAG, "Exception =" + e. toString () ;}}}); t. start (); try {t. join ();} catch (InterruptedException e) {// TODO Auto-generated catch blocke. PrintStackTrace ();} Log. d (TAG, "access_token =" + access_token); return access_token;} @ Override protected void onDestroy () {// TODO Auto-generated method stub if (webview! = Null) {webview = null;} super. onDestroy ();}}

Through the above method, we can easily obtain the access_token required for uploading videos by Youku. After obtaining the access_token, we can set the access_token to the params parameter, in this way, we can upload videos to Youku! As follows:

MainActivity. java

Package sample; import java. io. file; import java. util. arrayList; import java. util. hashMap; import java. util. list; import org. apache. http. httpResponse; import org. apache. http. nameValuePair; import org. apache. http. client. entity. urlEncodedFormEntity; import org. apache. http. client. methods. httpPost; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. message. basicNameValuePair; import org. Apache. http. protocol. HTTP; import org. apache. http. util. entityUtils; import org. json. JSONObject; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. OS. environment; import android. util. log; import android. view. view; import android. view. view. onClickListener; import android. widget. progressBar; import android. widget. textView; import android. widget. toast; import com. Youku. uploader. IUploadResponseHandler; import com. youku. uploader. r; import com. youku. uploader. youkuUploader; public class MainActivity extends Activity implements OnClickListener {private ProgressBar progressBar; private TextView percent; private YoukuUploader uploader; private String CLIENT_ID = "percent"; private String CLIENT_SECRET = "percent "; private String code; pri Vate String redirect_uri; private String access_token; private String TAG = "MainActivity"; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Intent in = getIntent (); code = in. getStringExtra ("code"); access_token = in. getStringExtra ("access_token"); Log. d (TAG, "token =" + access_token); progressBar = (ProgressBar) findView ById (R. id. progressbar); percent = (TextView) findViewById (R. id. percent); uploader = YoukuUploader. getInstance (CLIENT_ID, CLIENT_SECRET, getApplicationContext (); bindEvents ();} private void bindEvents () {findViewById (R. id. upload ). setOnClickListener (this); findViewById (R. id. cancel ). setOnClickListener (this) ;}@ Overridepublic void onClick (View v) {switch (v. getId () {case R. id. upload: Thread tt = new Thread (New Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubHashMap <String, String> params = new HashMap <String, String> (); params. put ("username", "15718854035"); params. put ("password", "243979"); // set access_token to params. put ("access_token", access_token); Log. d (TAG, "access_token =" + access_token); HashMap <String, String> uploadInfo = new HashMap <String, String> (); uploadInfo. put ("Title", "small video"); uploadInfo. put ("tags", "original"); // uploadInfo. put ("file_name", "/mnt/sdcard2/download/dota2.mp4"); uploadInfo. put ("file_name", Environment. getExternalStorageDirectory () + File. separator + "sharemv.mp4"); Log. d (TAG, "params =" + params + "uploadInfo" + uploadInfo + "file_name" + uploadInfo. get ("file_name "). toString (); uploader. upload (params, uploadInfo, new IUploadResponseHandler () {@ Overridep Ublic void onStart () {Log. v (TAG, "onStart"); progressBar. setProgress (0); percent. setText ("Waiting") ;}@ Overridepublic void onSuccess (JSONObject response) {Log. v (TAG, "onSuccess" + response. toString (); String respStr = response. toString (). substring (13, response. toString (). length ()-2); String str = String. format ("http://v.youku.com/v_show/id_%s.html? From = y1.7-1.2 ", respStr); Log. v (TAG, "onSuccess" + "the uri is:" + str); Toast. makeText (getApplicationContext (), "response. toString () ", 0 ). show () ;}@ Overridepublic void onProgressUpdate (int counter) {Log. v (TAG, "onProgressUpdate" + counter + ""); progressBar. setProgress (counter); percent. setText (counter + "%") ;}@ Overridepublic void onFailure (JSONObject errorResponse) {Log. v (TAG, "onFailure" + errorResponse. toString () ;}@ Overridepublic void onFinished () {Log. v (TAG, "onFinished"); percent. setText ("finished") ;}}); tt. start (); break; case R. id. cancel: if (uploader. cancel () {progressBar. setProgress (0); percent. setText ("") ;}break ;}}}





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.