1.DoubBanoAuthActivity.java
package com.g.sharelib.douban;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.g.sharelib.ICallBack;
import com.g.sharelib.R;
import com.g.sharelib.ShareHelper;
public class DoubBanoAuthActivity extends Activity {
private WebView view;
private String title;
private String content;
private String url;
private String imgurl;
private String appkey;
private String appser;
private String apprecurl;
private DoubanToken token = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
title = getIntent().getStringExtra("title");
content = getIntent().getStringExtra("content");
url = getIntent().getStringExtra("url");
imgurl = getIntent().getStringExtra("imgurl");
appkey = getIntent().getStringExtra("appkey");
appser = getIntent().getStringExtra("appser");
apprecurl = getIntent().getStringExtra("apprecurl");
view = new WebView(this);
view.setWebViewClient(new MyWebViewClient());
setContentView(view);
view.loadUrl("https://www.douban.com/service/auth2/auth?client_id="
+ appkey + "&redirect_uri=" + apprecurl
+ "&response_type=code&scope=shuo_basic_r,shuo_basic_w");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_DOWN) {
cancel();
return true;
}
return super.onKeyDown(keyCode, event);
}
public static ICallBack iCallBack_;
private Handler handler = new Handler() {
public void dispatchMessage(Message msg) {
if (iCallBack_ != null)
if (msg.what == 0) {
iCallBack_.onComplete(null, ShareHelper.ACT_SHARE,
getString(R.string.doubanname),
ShareHelper.TYPE_DOUBAN);
} else if (msg.what == 1) {
iCallBack_.onCancel(null, ShareHelper.ACT_SHARE,
getString(R.string.share_cancel),
getString(R.string.doubanname),
ShareHelper.TYPE_DOUBAN);
} else if (msg.what == 2) {
iCallBack_.onFailure(null, ShareHelper.ACT_SHARE,
(String) msg.obj, getString(R.string.doubanname),
ShareHelper.TYPE_DOUBAN);
finish();
}
};
};
private void success() {
handler.sendEmptyMessage(0);
}
private void error(String msg) {
Message message = handler.obtainMessage();
message.what = 2;
message.obj = msg;
handler.sendMessage(message);
}
private void cancel() {
handler.sendEmptyMessage(1);
}
private void post(final String code) {
view.setEnabled(false);
new Thread() {
public void run() {
String result;
try {
LinkedList<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("client_id", appkey));
params.add(new BasicNameValuePair("client_secret", appser));
params.add(new BasicNameValuePair("redirect_uri", apprecurl));
params.add(new BasicNameValuePair("grant_type",
"authorization_code"));
params.add(new BasicNameValuePair("code", code));
HttpPost postMethod = new HttpPost(
"https://www.douban.com/service/auth2/token");
postMethod.setEntity(new UrlEncodedFormEntity(params,
"utf-8")); // 将参数填入POST
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(postMethod); // 执行POST方法
BufferedReader in = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
error(getString(R.string.connect_error));
return;
} catch (ClientProtocolException e) {
e.printStackTrace();
error(getString(R.string.connect_error));
return;
} catch (IOException e) {
e.printStackTrace();
error(getString(R.string.connect_error));
return;
}
Log.i("test", result);
try {
JSONObject jsonObject = new JSONObject(result);
token = new DoubanToken();
token.setAccess_token(jsonObject.getString("access_token"));
token.setDouban_user_name(jsonObject
.getString("douban_user_name"));
token.setDouban_user_id(jsonObject
.getString("douban_user_id"));
token.setExpires_in(jsonObject.getLong("expires_in"));
token.setRefresh_token(jsonObject
.getString("refresh_token"));
PreferencesUtil.setPreferences(DoubBanoAuthActivity.this,
"doubantoken", token);
} catch (JSONException e) {
e.printStackTrace();
error(getString(R.string.error_back));
}
String result1;
try {
LinkedList<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("source", appkey));
params.add(new BasicNameValuePair("text", content));
params.add(new BasicNameValuePair("rec_title", title));
params.add(new BasicNameValuePair("rec_url",
url == null ? apprecurl : url));
params.add(new BasicNameValuePair("rec_image", imgurl));
Log.i("test", params.toString());
HttpPost postMethod = new HttpPost(
"https://api.douban.com/shuo/v2/statuses/");
postMethod.setEntity(new UrlEncodedFormEntity(params,
"utf-8")); // 将参数填入POST
postMethod.addHeader("Authorization",
"Bearer " + token.getAccess_token());
BasicHttpParams httpParams = new BasicHttpParams();
ConnManagerParams.setTimeout(httpParams, 15000);
SSLSocketFactory ssf = MySSLSocketFactory
.getFixedSocketFactory();
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", ssf, 443));
ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(
httpParams, registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr,
httpParams);
HttpResponse response = httpClient.execute(postMethod); // 执行POST方法
BufferedReader in = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result1 = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
error(getString(R.string.connect_error));
return;
} catch (ClientProtocolException e) {
e.printStackTrace();
error(getString(R.string.connect_error));
return;
} catch (IOException e) {
e.printStackTrace();
error(getString(R.string.connect_error));
return;
}
Log.i("test", result1);
try {
JSONObject jsonObject = new JSONObject(result1);
String id = jsonObject.getString("id");
if (id != null && !id.equals(""))
success();
else
error(getString(R.string.error_back));
} catch (JSONException e) {
e.printStackTrace();
error(getString(R.string.error_back));
}
};
}.start();
finish();
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url == null) {
error(getString(R.string.auth_error));
return true;
}
// 获取code
String code = url
.substring(url.indexOf("code=") + "code=".length());
if (code.contains("&")) {
code = code.substring(0, code.indexOf("&"));
}
if (code == null) {
error(getString(R.string.auth_error));
return true;
}
Log.i("test", code);
post(code);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
}
2.DoubanToken.java
package com.g.sharelib.douban;
import java.io.Serializable;
public class DoubanToken implements Serializable {
private String access_token;
private String douban_user_name;
private String douban_user_id;
private long expires_in;
private String refresh_token;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getDouban_user_name() {
return douban_user_name;
}
public void setDouban_user_name(String douban_user_name) {
this.douban_user_name = douban_user_name;
}
public String getDouban_user_id() {
return douban_user_id;
}
public void setDouban_user_id(String douban_user_id) {
this.douban_user_id = douban_user_id;
}
public long getExpires_in() {
return expires_in;
}
public void setExpires_in(long expires_in) {
this.expires_in = expires_in;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
}
3.MySSLSocketFactory.java
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.g.sharelib.douban;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
/**
* This file is introduced to fix HTTPS Post bug on API < ICS see
* http://code.google.com/p/android/issues/detail?id=13117#c14 <p> </p> Warning! This omits SSL
* certificate validation on every device, use with caution
*/
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
/**
* Creates a new SSL Socket Factory with the given KeyStore.
*
* @param truststore A KeyStore to create the SSL Socket Factory in context of
* @throws NoSuchAlgorithmException NoSuchAlgorithmException
* @throws KeyManagementException KeyManagementException
* @throws KeyStoreException KeyStoreException
* @throws UnrecoverableKeyException UnrecoverableKeyException
*/
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[]{tm}, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
/**
* Makes HttpsURLConnection trusts a set of certificates specified by the KeyStore
*/
public void fixHttpsURLConnection() {
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}
/**
* Gets a KeyStore containing the Certificate
*
* @param cert InputStream of the Certificate
* @return KeyStore
*/
public static KeyStore getKeystoreOfCA(InputStream cert) {
// Load CAs from an InputStream
InputStream caInput = null;
Certificate ca = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
caInput = new BufferedInputStream(cert);
ca = cf.generateCertificate(caInput);
} catch (CertificateException e1) {
e1.printStackTrace();
} finally {
try {
if (caInput != null) {
caInput.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
} catch (Exception e) {
e.printStackTrace();
}
return keyStore;
}
/**
* Gets a Default KeyStore
*
* @return KeyStore
*/
public static KeyStore getKeystore() {
KeyStore trustStore = null;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// trustStore = KeyStore.getInstance("jks");
trustStore.load(null, null);
} catch (Throwable t) {
t.printStackTrace();
}
return trustStore;
}
/**
* Returns a SSlSocketFactory which trusts all certificates
*
* @return SSLSocketFactory
*/
public static SSLSocketFactory getFixedSocketFactory() {
SSLSocketFactory socketFactory;
try {
socketFactory = new MySSLSocketFactory(getKeystore());
socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
} catch (Throwable t) {
t.printStackTrace();
socketFactory = SSLSocketFactory.getSocketFactory();
}
return socketFactory;
}
/**
* Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
*
* @param keyStore custom provided KeyStore instance
* @return DefaultHttpClient
*/
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
try {
SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
文档看好久看不明白,这个没有用到sdk,因为是android里的所以不需要引包,不,http得引,能用的到的就用吧,intent传要穿的参数然后在handler.msg.what==1时候设置参数,具体参数 http://developers.do