文档章节

挑战独立开发项目能力___ITlanbao

抉择很难
 抉择很难
发布于 2015/11/26 11:10
字数 1719
阅读 57
收藏 1

  
    做了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.
 * <p>
 * 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.
 * </p>
 */
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.
     * <p>
     * <b>Note:</b> Android does not support the JKS keystore provider. For
     * android BKS should be used. See <a href="http://www.bouncycastle.org/">
     * BouncyCastle</a> for details.
     * </p>
     *
     * @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<NameValuePair> 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<NameValuePair> 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<NameValuePair> 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
    
    
    

© 著作权归作者所有

抉择很难
粉丝 6
博文 51
码字总数 26157
作品 0
海淀
程序员
私信 提问
程序员的噩梦,我的漏洞伤害了他人.......

对绝大多数人来说,都是些老生常谈的东西使他们噩梦连连:幽灵、蜘蛛,被戴着冰球面具的杀人狂追杀……但对另一些人来说,他们最害怕的东西就没那么常见了。 就拿软件开发者举例吧。如果你问...

梦想_在追逐
2015/09/17
101
0
2015最火十大Android开源项目,是个程序员你就该看看!

1.目前最火的android-image-slide-panel图片照片墙的加载和滑动特效 http://www.itlanbao.com/code/20150908/10000/100513.html 2.超高仿QuickNews新闻客户端源码 http://www.itlanbao.com/......

梦想_在追逐
2015/09/16
463
0
分享6大主流视图切换(View Transition)

1.不可思议的上下滑动AndroidSlidingUpPanel 源码:http://www.itlanbao.com/code/20150815/10000/100388.html 2.DragLayout高仿QQ侧滑效果 源码:http://www.itlanbao.com/code/20150815/1......

梦想_在追逐
2015/09/21
75
0
android特效按钮点击效果

android特效按钮点击效果,动画从里到外渐变放大散花效果,本例子适合做一些特效的app使用, 使用很简单,直接可以把里面代码拷贝过去, 项目来自:https://www.itlanbao.com 本项目主要由:...

拼一把
2015/12/24
328
0
2015Android移动开发应用主流菜单模式

1.Menu史上最牛的侧滑效果 http://www.itlanbao.com/code/20150909/10000/100518.html 2.炫酷MultiCardMenu叠加菜单 http://www.itlanbao.com/code/20150909/10000/100517.html 3.android me......

梦想_在追逐
2015/09/20
44
0

没有更多内容

加载失败,请刷新页面

加载更多

总结

一、设计模式 简单工厂:一个简单而且比较杂的工厂,可以创建任何对象给你 复杂工厂:先创建一种基础类型的工厂接口,然后各自集成实现这个接口,但是每个工厂都是这个基础类的扩展分类,spr...

BobwithB
45分钟前
4
0
java内存模型

前言 Java作为一种面向对象的,跨平台语言,其对象、内存等一直是比较难的知识点。而且很多概念的名称看起来又那么相似,很多人会傻傻分不清楚。比如本文我们要讨论的JVM内存结构、Java内存模...

ls_cherish
48分钟前
4
0
友元函数强制转换

友元函数强制转换 p522

天王盖地虎626
昨天
5
0
js中实现页面跳转(返回前一页、后一页)

本文转载于:专业的前端网站➸js中实现页面跳转(返回前一页、后一页) 一:JS 重载页面,本地刷新,返回上一页 复制代码代码如下: <a href="javascript:history.go(-1)">返回上一页</a> <a h...

前端老手
昨天
5
0
JAVA 利用时间戳来判断TOKEN是否过期

import java.time.Instant;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;/** * @descri......

huangkejie
昨天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部