Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 調用優酷SDK上傳視頻

Android 調用優酷SDK上傳視頻

編輯:關於Android編程

最近在研究用優酷的SDK來進行視頻上傳的功能,由於優酷的SDK只是提供了一個上傳的sample code,沒有涉及到授權的過程,對於新手來說,可能非常棘手,現在分享一下我的思路:
程序實現前我們先要到優酷開放平台下載SDK(下載地址:http://open.youku.com/down) 根據優酷SDK的說明,上傳過程主要分為以下7個步驟:

1. 新建android項目,引入YoukuUploadSDK-android jar包

2. 在MainActivity.java文件添加代碼如sample.java所示,添加相關參數

3. 文件夾layout下activity_main.xml添加控件

4. 生成代碼(xml文件代碼)

5. 連接android手機運行android項目生成apk(切記開啟開發者選項usb調試等)

6. 授權過程(獲取access_token)

7. 點擊upload上傳

 

其他的幾步按照文檔來做,應該不會有問題,下面重點說說步驟6的授權過程。

我們只能采用通用授權的方式(合作級別的授權方式需要收費),關於授權機制,請參考http://open.youku.com/docs/OAuth2.html。

大概思路就是,通過一個WebView來顯示授權頁面獲取授權碼(code),我們需要使用http方法get的方式來獲取授權碼(code),所需的參數請參考http://open.youku.com/docs/OAuth2.html?id=101,然後通過使用授權碼(code)來交換令牌即所謂的access_token,最後通過access_token來獲取上傳的權限。

代碼如下看代碼:

AndroidManifest.xml

 




    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
        
            
                

                
            
        
        
        
    

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.http.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_token;
	    private String CLIENT_ID = "38bae68624af4531";
		private String CLIENT_SECRET = "feb939fd882b449e1f022aa12fb9b06a";
		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); 
	        // 設置Web視圖
	           webview =(WebView)findViewById(R.id.webView1);
	           if(webview == null){
	        	   return;
	           }
	           
	   //下面這個鏈接大家可只要把client_id及redirect_uri後面的值換成我們申請優酷開發者帳號時優酷提供的及我們設置的回調地址就可以
	           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);
	           //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() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						String strUrl = "https://openapi.youku.com/v2/oauth2/token";
						 HttpResponse httpResponse = null;
				        HttpPost httpPost = new HttpPost(strUrl);
				        List params = new ArrayList();
				        params.add(new BasicNameValuePair("client_id", CLIENT_ID));//你申請優酷的client_id
				        params.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));//你申請優酷的client_secret
				        params.add(new BasicNameValuePair("grant_type", "authorization_code"));
				        params.add(new BasicNameValuePair("code", strCode));//剛剛獲取到的code
				        
				        params.add(new BasicNameValuePair("redirect_uri", REDIRECT_URL));//回調地址,必須跟網站的一樣
				  try {
				        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			            Log.d(TAG,"getToken () setEntity after");
			           
			            httpResponse = new DefaultHttpClient().execute(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獲取成功
			                
//			                Toast.makeText(getApplicationContext(), "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 block
				e.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();
	    }
	 
}

通過上述方法,我們可以很簡單地獲取優酷上傳視頻所需要的access_token,獲取了access_token以後,我們就可以將access_token設置到params的參數中,這樣我們就能實現上傳視頻到優酷了!如下:

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 = "38bae68624af4531";
	private String CLIENT_SECRET = "feb939fd882b449e1f022aa12fb9b06a";
	private String code;
	private String redirect_uri;
	private String access_token;
	private String TAG ="MainActivity";
	@Override
	protected 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) findViewById(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);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.upload:
			
			Thread tt = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					HashMap params = new HashMap();
					params.put("username", "15718854035");
					params.put("password", "243979");
					//這裡需要將access_token設置到參數中
					params.put("access_token",access_token);
					Log.d(TAG, "access_token="+access_token);
					HashMap uploadInfo = new HashMap();
					uploadInfo.put("title", "小視頻");
					uploadInfo.put("tags", "原創");
//					 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() {

						@Override
						public void onStart() {
							Log.v(TAG, "onStart");
							progressBar.setProgress(0);
							percent.setText("等待中");
						}

						@Override
						public 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();
						}

						@Override
						public void onProgressUpdate(int counter) {
							Log.v(TAG,"onProgressUpdate"+ counter + "");
							progressBar.setProgress(counter);
							percent.setText(counter + "%");
						}

						@Override
						public void onFailure(JSONObject errorResponse) {
							Log.v(TAG,"onFailure"+ errorResponse.toString());
						}

						@Override
						public void onFinished() {
							Log.v(TAG, "onFinished");
							percent.setText("完成");
						}
					});
				}
			});
			tt.start();
			break;

		case R.id.cancel:
			if (uploader.cancel()) {
				progressBar.setProgress(0);
				percent.setText("");
			}
			break;
		}
	}
	
}


 

 

 



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved