搜索遍了所有的网站关于淘宝登录的网站资源,近乎全是一大抄用的第三方诚迈的一个第三方API来做的,这也是我个人非常不不喜欢的,并且淘宝也已经给予下架了,最不喜欢借用别人的jar包,仔细看了taobao的api开发包,发觉这个android api做的最的有点混乱,但是还是得仔细看,甚至不漏掉一个字母,经过四天的细读,终于解决,希望对同样有这种困huo的朋友们一个帮助
本思路就是得到淘宝给出的授权码,然后再取得acc_token,这样就一切OK了
/*
* 测试只允许一天5000次
* My:wxl_954136
* App Key:*****
* App Secret:******** */
package com.act.taobao;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import sun.misc.BASE64Encoder;
import com.act.Base;
import com.act.R;
import com.function.normal.NormalTips;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.WebUtils;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.request.UserBuyerGetRequest;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.request.WidgetLoginstatusGetRequest;
import com.taobao.api.response.TradesSoldGetResponse;
import com.taobao.api.response.UserBuyerGetResponse;
import com.taobao.api.response.UserGetResponse;
import com.taobao.api.response.WidgetLoginstatusGetResponse;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Taobao extends Activity {
private WebView mWebView=null;
private EditText etAddress = null;
private TextView etHref = null;
// http://wap.taobao.com/mtop/bind_app_result.htm?sid=8b8101660406429abe4dd71313890a6e &ac=1&appkey=******&callback_url=null
// http://my.open.taobao.com/auth/authorize.htm?appkey=21341573&encode=utf-8 获得sessionKey是什么意思
private final String appkey = "******";
private final String secret = "**************";
private String P_SHOUQUAN = ""; //获得授权码的值
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* 1.这里特别注意以下三句话的放置顺序
* 2.特别注意AndroidManifest.xml中的activty的配置文件,必须重定义,否则会失败
* <activity
android:name="com.act.taobao.Taobao"
android:theme="@style/CustomTaobaoLoginTheme"
android:label="@string/title_activity_taobao" >
</activity>
*/
//
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.taobao_layout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.taobao_layout_login_titlebar);
initForm();
}
public String getURLContent(String _url)
{
String urlAddress = _url;
String resultData = "";
URL url = null;
try {
url = new URL(urlAddress);
} catch (Exception e) {
e.printStackTrace();
}
if (url != null) {
try {
// 使用HttpUrlConnection打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 得到读取内容流
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// 为输出创建BufferedReader
BufferedReader br = new BufferedReader(in);
String readLine = "";
// 使用循环来读取获得的数据流
while ((readLine = br.readLine()) != null) {
resultData += readLine + "\n";
}
in.close();
conn.disconnect();
// 显示内容
// if (resultData != null) {
// etHref.setText(resultData);
// } else {
// etHref.setText("读取内容为空!!!");
// }
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.d("url", "----->URL is NUll...");
}
return resultData ;
}
private void initForm()
{
etAddress = (EditText)this.findViewById(R.id.taobao_wv_address);
etHref = (TextView)this.findViewById(R.id.taobao_login_href);
mWebView = (WebView)this.findViewById(R.id.taobao_login_wv1);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true); //有自动放大缩小功能
mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
mWebView.setWebViewClient(new MyWebViewClient());
// http://container.api.taobao.com/container?appkey=21341573
// mWebView.loadUrl("http://m.taobao.com");
// Uri uri = Uri.parse("https://oauth.taobao.com/authorize?response_type=token&view=wap&redirect_uri=sample://authresult&client_id="+TopConfig.APPKEY);
// Intent it = new Intent(Intent.ACTION_VIEW, uri);
// startActivity(it);
// https://oauth.taobao.com/authorize?response_type=code&client_id=21341573&redirect_uri=&state=1212&scope=item&view=web
/*
* 注意此网站有demo下载,有专门针对app的
*下载: http://open.taobao.com/doc/detail.htm?spm=0.0.0.21.d7FMul&id=118#s7
*1.https://oauth.taobao.com/authorize?response_type=code&client_id=21341573&redirect_uri=urn:ietf:wg:oauth:2.0:oob&view=wap
*这一种是直接获取 专为application而设,建议采用第一种
*2.https://oauth.taobao.com/authorize?response_type=token&view=wap&redirect_uri=&client_id=21341573
*/
//授权码即为sessionKey
//https://oauth.taobao.com/authorize?response_type=code&client_id=21341573&redirect_uri=urn:ietf:wg:oauth:2.0:oob&view=wap
String _url = "https://oauth.taobao.com/authorize?response_type=code&client_id=21341573&redirect_uri=urn:ietf:wg:oauth:2.0:oob&state=1212&scope=item&view=wap" ;
mWebView.loadUrl(_url);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.taobao_menu, menu);
return true;
}
//提取网页源码
//参照网页
final class MyWebViewClient extends WebViewClient{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url); //此方法始终在一同一个webView 中显示
return true;
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d("WebView","onPageStarted");
super.onPageStarted(view, url, favicon);
etAddress.setText(url);
etHref.setText(url);
}
public void onPageFinished(WebView view, String url) {
Log.d("WebView","onPageFinished ");
view.loadUrl("javascript:window.local_obj.showSource('<head>'+" +
"document.getElementsByTagName('html')[0].innerHTML+'</head>');");
super.onPageFinished(view, url);
}
}
final class InJavaScriptLocalObj {
public void showSource(String html) {
;
if (html.indexOf("授权码获取成功") > 0 )
{
int start = html.indexOf("<p>授权码:") + "<p>授权码:".length();
int end = html.indexOf("</p>");
String result = html.substring(start,end).trim();
// mWebView.loadData(result, "text/html", "UTF-8") ;
P_SHOUQUAN = result;
wxl();
}
}
public void wxl()
{
String redirect_url = "urn:ietf:wg:oauth:2.0:oob";
String tbPostSessionUrl = "https://oauth.taobao.com/token"; //获取访问令牌
// String sessionKey = P_SHOUQUAN;
Map<String, String> param = new HashMap<String, String>();
param.put("grant_type", "authorization_code");
param.put("code", P_SHOUQUAN);
param.put("client_id", appkey);
param.put("client_secret", secret);
param.put("redirect_uri", redirect_url);
param.put("scope", "item");
param.put("view", "wap");
param.put("state", "1212");
try{
String responseJson=WebUtils.doPost(tbPostSessionUrl, param, 3000, 3000);
/*思路:先获取授权码,然后再获取访问令牌access_token
* 返回数据格式如下
*参照如下淘宝网站:http://open.taobao.com/doc/detail.htm?spm=0.0.0.18.jyWNwK&id=118
* {
"w2_expires_in": 0,
"taobao_user_id": "263685215",
"taobao_user_nick": "%E5%95%86%E5%AE%B6%E6%B5%8B%E8%AF%95%E5%B8%90%E5%8F%B752",
"w1_expires_in": 1800,
"re_expires_in": 0,
"r2_expires_in": 0,
"expires_in": 86400,
"token_type": "Bearer",
"refresh_token": "6200e1909ca29b04685c49d67f5ZZ3675347c0c6d5abccd263685215",
"access_token": "6200819d9366af1383023a19907ZZf9048e4c14fd56333b263685215",
"r1_expires_in": 1800
}
*/
JSONObject ansyJson = new JSONObject(responseJson); //JSON解析
String _access_token = ansyJson.getString("access_token");
String _refesh_token = ansyJson.getString("refresh_token");
// mWebView.loadData(_access_token, "text/html", "UTF-8") ;
//用web address成功返回xml 这种方法不好,每次都要解析xml,并且要借助webView,建议用json
// String _access_user_url = "https://eco.taobao.com/router/rest?" +
// "access_token=" + _access_token +
// "&method=taobao.user.buyer.get&v=2.0&fields=user_id,nick,sex,buyer_credit,avatar,has_shop,vip_info";
//
// mWebView.loadUrl(_access_user_url);
//
mWebView.loadData("取值成功:", "text/html", "UTF-8") ;
//Access Token即用户授权后颁发的session key:网站有说明http://open.taobao.com/doc/detail.htm?spm=0.0.0.29.RQv96m&id=118
//所有的都可以这么做,不用webView了,直接用taobao的包 WebUtil
//这里有个问题,如果是官方文档,里面传参数有个sign,那时要经过加密的,这时不用加密,如果已经取得access token,此时就不用了
String _access_user_url = "https://eco.taobao.com/router/rest?" +
"access_token=" + _access_token +
"&method=taobao.user.buyer.get&v=2.0&fields=user_id,nick,sex,buyer_credit,avatar,has_shop,vip_info&format=json";
String _userJson=WebUtils.doPost(_access_user_url, null, 3000, 3000);
/* json格式如下
{"user_buyer_get_response":
{"user":
{
"avatar":"http://img./sns_logo/i1/T1xayaXXNmXXb1upjX.jpg",
"buyer_credit":{"good_num":580,"level":7,"score":580,"total_num":580},
"has_shop":false,"nick":"wxl_954136","sex":"m","user_id":23625237,"vip_info":"vip4"
}
}
}
*/
Log.d("HTML", "0======" + _userJson );
JSONObject ansyUserJson = new JSONObject(_userJson).getJSONObject("user_buyer_get_response").getJSONObject("user"); //JSON解析
Log.d("HTML", "1======" + ansyUserJson.getString("nick") );
mWebView.loadData( _userJson, "text/html", "UTF-8") ;
}catch(Exception eg){
Log.d("HTML", "ERROR:" + eg.getMessage());
etHref.setText("E===:ETT" + eg.getMessage());
mWebView.loadData("GET--:ERR" + eg.getMessage(), "text/html", "UTF-8") ;
}
}
}
}
|