SinaUtil 新浪微博工具类
package com.ichances.fashionweek.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.URLEncoder; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Map; import java.util.zip.GZIPInputStream; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnRouteParams; 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.entity.ByteArrayEntity; 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.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.net.Uri; import android.net.wifi.WifiManager; /** * 新浪微博工具,分享文字、图片、图片url */ public class SinaUtil { private static final int SET_CONNECTION_TIMEOUT = 50000; private static final int SET_SOCKET_TIMEOUT = 200000; private static final String BOUNDARY = "7cd4a6d158c"; private static final String MP_BOUNDARY = "--" + BOUNDARY; private static final String END_MP_BOUNDARY = "--" + BOUNDARY + "--"; private static final String MULTIPART_FORM_DATA = "multipart/form-data"; /** * 发送一条文字微博或者带图片Url的微博 * * @param context * @param url * @param params * 包含字段:format、status(不需要编码)、access_token,若需要图片Url,添加url字段, * 且注意需要应用开通高级接口权限 * ,说明网址http://open.weibo.com/wiki/%E9%AB%98%E7%BA%A7%E6 * %8E%A5%E5%8F%A3%E7%94%B3%E8%AF%B7 * @return */ public static String postContent(Context context, String url, Map<String, Object> params) { try { HttpClient client = getNewHttpClient(context); HttpUriRequest request = null; ByteArrayOutputStream bos = null; HttpPost post = new HttpPost(url); byte[] data = null; bos = new ByteArrayOutputStream(1024 * 50); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); String postParam = encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); request = post; HttpResponse response = client.execute(request); // 用于查看返回的错误码 // StatusLine status = response.getStatusLine(); // int statusCode = status.getStatusCode(); return read(response); } catch (IOException e) { e.printStackTrace(); } return ""; } /*** * 发送一条带图片文件的微博 * * @param context * @param url * @param params * 包含字段:format、status(不需要编码)、access_token * @param filePath * 本地图片的绝对路径 * @return */ public static String postContentWithFile(Context context, String url, Map<String, Object> params, String filePath) { try { HttpClient client = getNewHttpClient(context); HttpUriRequest request = null; HttpPost post = new HttpPost(url); ByteArrayOutputStream bos = null; byte[] data = null; bos = new ByteArrayOutputStream(1024 * 50); paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); imageContentToUpload(bos, filePath); data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); request = post; HttpResponse response = null; response = client.execute(request); // 获得发送状态 // StatusLine status = response.getStatusLine(); // int statusCode = status.getStatusCode(); return read(response); } catch (IOException e) { e.printStackTrace(); } return ""; } /** * Read http requests result from response . * * @param response * : http response by executing httpclient * * @return String : http response content */ private static String read(HttpResponse response) { String result = ""; HttpEntity entity = response.getEntity(); InputStream inputStream; try { inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); Header header = response.getFirstHeader("Content-Encoding"); if (header != null && header.getValue().toLowerCase().indexOf("gzip") > -1) { inputStream = new GZIPInputStream(inputStream); } // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[512]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream result = new String(content.toByteArray()); } catch (IOException e) { e.printStackTrace(); } return result; } private static HttpClient getNewHttpClient(Context context) { try { KeyStore trustStore = KeyStore.getInstance(KeyStore .getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager( params, registry); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); WifiManager wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { // 获取当前正在使用的APN接入点 Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { // 游标移至第一条记录,当然也只有一条 String proxyStr = mCursor.getString(mCursor .getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter( ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; } catch (Exception e) { return new DefaultHttpClient(); } } /** * change Map to String, and add '&' between every two map * * @param httpParams * @return */ public static String encodeParameters(Map<String, Object> httpParams) { if (null == httpParams) { return ""; } StringBuilder buf = new StringBuilder(); int j = 0; for (String key : httpParams.keySet()) { if (j != 0) { buf.append("&"); } try { buf.append(URLEncoder.encode(key, "UTF-8")) .append("=") .append(URLEncoder.encode(httpParams.get(key) .toString(), "UTF-8")); } catch (java.io.UnsupportedEncodingException neverHappen) { } j++; } return buf.toString(); } /** * Upload weibo contents into output stream . * * @param baos * : output stream for uploading weibo * @param params * : post parameters for uploading * @return void */ private static void paramToUpload(OutputStream baos, Map<String, Object> map) { for (String key : map.keySet()) { StringBuilder temp = new StringBuilder(10); temp.setLength(0); temp.append(MP_BOUNDARY).append("\r\n"); temp.append("content-disposition: form-data; name=\"").append(key) .append("\"\r\n\r\n"); temp.append(map.get(key).toString()).append("\r\n"); byte[] res = temp.toString().getBytes(); try { baos.write(res); } catch (IOException e) { e.printStackTrace(); } } } /** * Upload image into output stream . * * @param out * : output stream for uploading weibo * @param imgpath * : bitmap for uploading * @return void */ private static void imageContentToUpload(OutputStream out, String filePath) { File file = new File(filePath); if (!file.exists()) { return; } Bitmap imgpath = BitmapFactory.decodeFile(filePath); StringBuilder temp = new StringBuilder(); temp.append(MP_BOUNDARY).append("\r\n"); temp.append("Content-Disposition: form-data; name=\"pic\"; filename=\"") .append("news_image.png").append("\"\r\n"); String filetype = "image/png"; temp.append("Content-Type: ").append(filetype).append("\r\n\r\n"); byte[] res = temp.toString().getBytes(); try { out.write(res); imgpath.compress(CompressFormat.PNG, 75, out); out.write("\r\n".getBytes()); out.write(("\r\n" + END_MP_BOUNDARY).getBytes()); } catch (IOException e) { e.printStackTrace(); } } public static class MySSLSocketFactory extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager 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, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } } }