标签:优酷视频上传
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
<?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.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.RECORD_AUDIO"/> <!-- 这个权限用于进行网络定位 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 这个权限用于访问GPS定位 --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位 --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 获取运营商信息,用于支持提供运营商信息相关的接口 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位 --> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <!-- 用于读取手机当前的状态 --> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- SD卡读取权限,用户写入离线定位数据 --> <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.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<NameValuePair> params = new ArrayList<NameValuePair>(); 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<String, String> params = new HashMap<String, String>(); params.put("username", "15718854035"); params.put("password", "243979"); //这里需要将access_token设置到参数中 params.put("access_token",access_token); Log.d(TAG, "access_token="+access_token); HashMap<String, String> uploadInfo = new HashMap<String, String>(); 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; } } }
标签:优酷视频上传
原文地址:http://blog.csdn.net/shineflowers/article/details/46624823