挑战独立开发项目能力--IT蓝豹

                     
    做了5年的android开发,今天没事写写刚入行不久的时候第一次独立开发项目的心得体会,
    当时我刚工作8个月,由于公司运营不善倒闭了,在2011年3月份我开始准备跳槽,
    看了一周android笔试题和面试题后,然后就去找工作,当时去面试的时候说自己有独立项目开发的经验。
    结果面上了几家公司,后来选择一家游戏公司,开始游戏开发的生涯。当时我去的时候就android组就我一个人,
    也没有人带领,去公司一个月后公司决定要我把网游游戏移植到手游,那时候确实没有独立开发项目的经验。
    但是又只有一个人做,没办法只有自己慢慢研究,那时候没有像现在资源多,网上随便找。
    还是坚持慢慢从网络框架一步一步开始搭建。当时独立做完项目后感觉个人技术能力瞬间提高了很多,因为不在还怕独立承担项目了。
    希望我的感受能给同样刚入行的朋友能给与帮助。如今本人自己做一个技术网站:IT蓝豹(www.itlanbao.com)
        当时使用的网络框架是HttpClient,先实现ReceiveDataListener接口用来接收数据返回,然后设置如下代码调用
        
    调用方法:
    private void initHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = HttpClientFactory
                    .newInstance(Constants.CONNECTION_TIMEOUT);
            mHttpTransport = new HttpTransport(mHttpClient);
            mHttpTransport.setReceiveDataListener(this);
        }
    }
    
    
网络请求代码部分如下:HttpClientFactory类
         
        
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
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.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;

/**
 * A factory class to obtain a setup {@link HttpClient} instance to be used
 * among multiple threads. This instance should be kept open throughout the
 * applications lifetime and must only be closed if the client is not needed
 * anymore.
 *


 * This factory will never return a singleton such that each call to
 * {@link HttpClientFactory#newInstance(int, KeyStore)} results in a new
 * instance. Commonly only one call to this method is needed for an applicaiton.
 *


 */
public class HttpClientFactory {

    /**
     * Creates a new HttpClient instance setup with the given {@link KeyStore}.
     * The instance uses a multi-threaded connection manager with a
     * max-connection size set to 10. A connection is released back to the pool
     * once the response {@link InputStream} is closed or read until EOF.
     *


     * Note: Android does not support the JKS keystore provider. For
     * android BKS should be used. See
     * BouncyCastle
for details.
     *


     *
     * @param aConnectionTimeout
     *            the connection timeout for this {@link HttpClient}
     * @param aKeyStore
     *            a cryptographic keystore containing CA-Certificates for
     *            trusted hosts.
     * @return a new {@link HttpClient} instance.
     * @throws KeyManagementException
     *             If the {@link KeyStore} initialization throws an exception
     * @throws NoSuchAlgorithmException
     *             if ssl socket factory does not support the keystores
     *             algorithm
     * @throws KeyStoreException
     *             if the {@link KeyStore} can not be opened.
     * @throws UnrecoverableKeyException
     *             I have not idea when this happens :)
     */
    public static HttpClient newInstance(int aConnectionTimeout/*
                                                                * , KeyStore
                                                                * aKeyStore
                                                                */)
    /*
     * throws KeyManagementException, NoSuchAlgorithmException,
     * KeyStoreException, UnrecoverableKeyException
     */{
        final HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpConnectionParams.setConnectionTimeout(params, aConnectionTimeout);
        HttpConnectionParams.setTcpNoDelay(params, false);

        // final SSLSocketFactory socketFactory = new
        // SSLSocketFactory(aKeyStore);
        // socketFactory
        // .setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", new PlainSocketFactory(), 80));
        // registry.register(new Scheme("https", socketFactory, 443));
        // connection pool is limited to 20 connections
        ConnManagerParams.setMaxTotalConnections(params, 20);
        // ServoConnPerRoute limits connections per route / host - currently
        // this is a constant
        ConnManagerParams.setMaxConnectionsPerRoute(params,
                new AndhatConnPerRoute());

        final DefaultHttpClient defaultHttpClient = new DefaultHttpClient(
                new ThreadSafeClientConnManager(params, registry), params);

        return defaultHttpClient;
    }
}
    
    
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、    
HttpTransport 类代码如下:


package com.andhat.android.http;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

import java.net.URI;
import java.util.List;

import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;

import org.apache.http.conn.params.ConnRoutePNames;

import org.apache.http.protocol.HTTP;

import com.andhat.android.utils.Constants;
import com.andhat.android.utils.UserPreference;
import com.andhat.android.utils.Utils;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class HttpTransport {
    private final HttpClient _client;

    private ReceiveDataListener mRecListener;
    public final static int RECEIVE_DATA_MIME_STRING = 0;
    public final static int RECEIVE_DATA_MIME_PICTURE = 1;
    public final static int RECEIVE_DATA_MIME_AUDIO = 2;

    public HttpTransport(HttpClient aClient) {
        _client = aClient;
    }

    /**
     * 关闭连接
     */
    public void shutdown() {
        if (_client != null && _client.getConnectionManager() != null) {
            _client.getConnectionManager().shutdown();
        }
    }

    
    public void post(boolean proxy, Handler handler, String url,
            List params, int mime)
            throws ClientProtocolException, IOException {
        if (proxy) {
            postByCMCCProxy(url, handler, params, mime);

        } else {
            post(URI.create(url), handler, params, mime);
        }
    }

    private void postByCMCCProxy(String url, Handler handler,
            List params, int mime)
            throws ClientProtocolException, IOException {

        String host = getHostByUrl(url);
        String port = getPortByUrl(url);
        
        
        HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
        HttpHost target = new HttpHost(host, Integer.parseInt(port), "http");
        _client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        HttpPost post = new HttpPost(url);
        if (params != null && params.size() > 0) {
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        }

        HttpResponse httpResponse = _client.execute(target, post);

        StatusLine statusLine = httpResponse.getStatusLine();
        final int status = statusLine.getStatusCode();
        if (status != HttpStatus.SC_OK) {
            String message = "HTTP Response code: "
                    + statusLine.getStatusCode() + " - "
                    + statusLine.getReasonPhrase();
            Log.e("connectmsg", message);
            throw new IOException(message);
        }

        InputStream in = httpResponse.getEntity().getContent();
        long length = httpResponse.getEntity().getContentLength();
        byte[] data = receiveData(null,url, in, length);
        if (mRecListener != null) {
            mRecListener.receive(data, mime);
        }
        handler.sendEmptyMessage(Constants.MSG_THAN_FILE);
        post.abort();
    }

    // http://220.113.3.254:8080/AnimeInterface/Interface.do
    private void post(URI uri, Handler handler, List params,
            int mime) throws ClientProtocolException, IOException {
        Log.e("Goo", "HttpTransport post()");
        // try {
        HttpPost post = new HttpPost(uri);
        if (params != null && params.size() > 0) {
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        }
        HttpResponse httpResponse = _client.execute(post);
        StatusLine statusLine = httpResponse.getStatusLine();
        final int status = statusLine.getStatusCode();
        if (status != HttpStatus.SC_OK) {
            String message = "HTTP Response code: "
                    + statusLine.getStatusCode() + " - "
                    + statusLine.getReasonPhrase();
            shutdown();
            throw new IOException(message);
        }

        InputStream in = httpResponse.getEntity().getContent();
        long length = httpResponse.getEntity().getContentLength();
        byte[] data = receiveData(null,uri.toString(), in, length);
        if (mRecListener != null) {
            mRecListener.receive(data, mime);
        }
        handler.sendEmptyMessage(Constants.MSG_THAN_FILE);
        post.abort();
        // } catch (IllegalStateException e) {
        // Log.e("Goo", "程序异常");
        // shutdown();
        // e.printStackTrace();
        // }
    }

    public void get(boolean proxy, Context context, Handler hanlder,
            String url, int mime) throws IOException {
        if (proxy) {
            getByCMCCProxy(url, context, hanlder, mime);
        } else {
            get(URI.create(url), context, hanlder, mime);
        }
        UserPreference.ensureIntializePreference(context);
    }

    private String getPortByUrl(String url) {
        int start = url.indexOf(":");
        if (start < 0)
            return "80";
        int s = url.indexOf(":", start + 1);
        if (s < 0)
            return "80";
        int e = url.indexOf("/", s + 1);
        if (e < 0) {
            return url.substring(s + 1);
        } else {
            return url.substring(s + 1, e);
        }
    }

    private String getHostByUrl(String url) {
        int start = url.indexOf(":");
        if (start < 0)
            return null;
        int s = url.indexOf(":", start + 1);
        if (s >= 0)
            return url.substring(0, s);
        int e = url.indexOf("/", start + 3);
        if (e >= 0) {
            return url.substring(0, e);
        } else {
            return url;
        }
    }

    private void getByCMCCProxy(String url, Context context, Handler handler,
            int mime) throws ClientProtocolException, IOException {
        Log.e("request url", url);
        // try {
        String host = getHostByUrl(url);
        String port = getPortByUrl(url);
        HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
        HttpHost target = new HttpHost(host, Integer.parseInt(port), "http");
        _client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        HttpGet get = new HttpGet(url);
        HttpResponse httpResponse = _client.execute(target, get);
        StatusLine statusLine = httpResponse.getStatusLine();
        final int status = statusLine.getStatusCode();
        Log.e("getByCMCCProxystatus", "" + status);
        if (status != HttpStatus.SC_OK) {
            String message = "HTTP Response code: "
                    + statusLine.getStatusCode() + " - "
                    + statusLine.getReasonPhrase();
            Log.e("getByCMCCProxy", message);
            throw new IOException(message);
        }
        InputStream in = httpResponse.getEntity().getContent();
        long length = httpResponse.getEntity().getContentLength();
        Log.e("Goo", "GetRequest Entity Length:" + String.valueOf(length));
        byte[] data = receiveData(context,url.toString(), in, length);
        Log.e("Goo", "data length:" + String.valueOf(data.length));
        if (mRecListener != null && length == data.length) {
            mRecListener.receive(data, mime);
        }
        handler.sendEmptyMessage(Constants.MSG_THAN_FILE);
        get.abort();
        // } catch (Exception e) {
        // shutdown();
        // e.printStackTrace();
        // }
    }

    private void get(URI uri, Context context, Handler handler, int mime)
            throws IOException {
        // try {
        final HttpGet get = new HttpGet(uri);
        HttpResponse httpResponse = _client.execute(get);
        StatusLine statusLine = httpResponse.getStatusLine();
        final int status = statusLine.getStatusCode();
        if (status != HttpStatus.SC_OK) {
            String message = "HTTP Response code: "
                    + statusLine.getStatusCode() + " - "
                    + statusLine.getReasonPhrase();
            throw new IOException(message);
        }
        InputStream in = httpResponse.getEntity().getContent();
        long downloadLength = httpResponse.getEntity().getContentLength();
        byte[] data = receiveData(context,uri.toString(), in, downloadLength);
        if (mRecListener != null) {
            mRecListener.receive(data, mime);
        }
        handler.sendEmptyMessage(Constants.MSG_THAN_FILE);
        get.abort();
        // } catch (IllegalStateException e) {
        // shutdown();
        // e.printStackTrace();
        // }
    }

    public byte[] receiveData(Context context,String url, InputStream in, long length)
            throws IOException {
        ByteArrayOutputStream bos = null;
        int downloadSize = 0;
        byte[] retval = null;
        String str = url;
        String[] s = str.split("/");
        for (String s1 : s) {
            if (s1.contains(".") && s1.endsWith(".gif")
                    || s1.endsWith(".amr")) {
                saveFailFile(context,s1);
                Log.e("Goo_downLoadSize", "fileName:"+s1);
            }
        }
        try {
            bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;

            while ((len = in.read(buf)) != -1) {
                bos.write(buf, 0, len);
                downloadSize = len + downloadSize;
            }
            Log.e("Goo_downLoadSize", "downloadSize:"+downloadSize+"");
            Log.e("Goo_downLoadSize", "length:"+length+"");
            if (downloadSize==length&&downloadSize!=-1) {
                saveFailFile(context,null);
            }
            retval = bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                close(in);
                close(bos);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return retval;
    }

    private void saveFailFile(Context context,String str) {
        UserPreference.ensureIntializePreference(context);
        UserPreference.save("fail_file", str);
    }

    private void close(Closeable c) {
        if (c == null) {
            return;
        }
        try {
            c.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void setReceiveDataListener(ReceiveDataListener listener) {
        mRecListener = listener;
    }

    public interface ReceiveDataListener {
        public void receive(byte[] data, int mime);
    }
}


//最后网络AndhatConnPerRoute
/*
 * Copyright (C) 2008-2009 Servo Software Inc.
 */
package com.andhat.android.http;

import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.routing.HttpRoute;

/**
 * Simple implementation of {@link ConnPerRoute} which limits the connections
 * per host route to a constant value;
 */
class AndhatConnPerRoute implements ConnPerRoute {

    private final int _conPerRoute;

    AndhatConnPerRoute(int aConPerRoute) {
        _conPerRoute = aConPerRoute;
    }

    AndhatConnPerRoute() {
        this(20);
    }

    /**
     * {@inheritdoc}
     *
     * @see org.apache.http.conn.params.ConnPerRoute#getMaxForRoute(org.apache.http.conn.routing.HttpRoute)
     */
    public int getMaxForRoute(HttpRoute aHttproute) {
        // TODO(simonw): check this once service locator is setup
        return _conPerRoute;
    }

}

    
    
    
文章来源IT蓝豹:www.itlanbao.com

创新互联建站主要从事成都做网站、成都网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务福田,十多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:028-86922220


文章标题: 挑战独立开发项目能力--IT蓝豹
文章起源:http://scyanting.com/article/jpieeg.html