2019独角兽企业重金招聘Python工程师标准>>>

做了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

转载于:https://my.oschina.net/u/2461971/blog/535802

挑战独立开发项目能力___ITlanbao相关推荐

  1. 6个经典Python项目让你快速具备独立开发能力

    最近打算录制一套视频,这个课程大约需要学习四周的时间,方便大家学习. 让你快速具备独立开发能力的6个经典Python项目如下: 一 600行代码项目 项目一:简单计算器 实现Python命令行操作的计 ...

  2. 独立开发变现周刊(第41期):一个开源项目一个人每月收入8万美金

    分享独立开发.产品变现相关内容,每周五发布. 目录 1.Budibase: 开源的低代码平台 2.沃尔玛通过SEO每月获得2.5亿流量的秘密 3.DesignJoy: 一个人的设计团队,月收入9万美金 ...

  3. 独立开发变现周刊(第43期):业余项目成功的秘密

    分享独立开发.产品变现相关内容,每周五发布. 目录 1.Threadstart: 推文编写和定时发布工具 2.Bardeen:自动化浏览器插件,取代你的重复繁琐操作 3.Podia: 对用户的极度专注 ...

  4. [小白的Web全栈之旅]独立开发电子商务网站--项目创建+数据库开发

    哈喽大家好,今天博主要讲解的是独立开发电子商务网站的第五篇--项目创建+数据库开发,想要预览整个系列博客的参考目录请点击这里 在本博客,博主会讲解: 项目创建 PHP连接MySQL 创建数据表 数据的 ...

  5. [小白的Web全栈之旅]独立开发电子商务网站--项目介绍

    Web开发,是一个看似简单,实际复杂的工程,需要包括但不限于设计师.前端开发.后端开发的程序员们来开发,而Web全栈开发,是一种carry全场,具备页面设计,前端开发,后端开发等多个技能于一身的大神程 ...

  6. 在一个软件开发项目中进行实际日程安排的十二点提示(转)

    Laura Rose , QE Manager, Rational<?XML:NAMESPACE PREFIX = O /> <?XML:NAMESPACE PREFIX = ST1 ...

  7. 软件开发项目中进行实际日程安排

    转自:http://www.ibm.com/developerworks/cn/rational/rationaledge/content/sep05/rose/ 你是否有足够的能力领导一个软件开发项 ...

  8. 独立开发变现周刊(第65期): 个人爱好发展成一项36万美元/年的NFTs业务

    分享独立开发.产品变现相关内容,每周五发布. 目录 1.KTool: 最简单的方式发送网络文章到Kindle 2.Koodo Reader: 一个跨平台的电子书阅读器 3.个人爱好发展成一项36万美元 ...

  9. 比较 Unity 与 Unreal 的 VR、MR 或 AR 开发项目

    Unity vs Unreal - how to decide which engine to use in your next XR project Unity vs Unreal--如何决定在你的 ...

最新文章

  1. DevExpress的TreeList实现自定义节点NodeCell的背景颜色和前景色
  2. Python:windows程序打包
  3. python 3.5opencv 环境搭建_Python3.5+openCv进行人脸识别的环境搭建(Windows下)
  4. MySQL子查询介绍
  5. matlab fminimax 例子,Matlab应用实例(8)—fminimax
  6. 大数据_Hbase-API访问_Java操作Hbase_封装操作数据的工具类---Hbase工作笔记0015
  7. (二十二)【模电】(波形的发生与信号的转换)电压比较器
  8. 面板数据,面板数据的三种基本模型
  9. python #hsv空间中Hue色度/色调在色相环上的角#冷暖色调 在色相环上的范围
  10. 金蝶K/3 Cloud 实施笔记
  11. 基本概念:线与逻辑、锁存器、缓冲器、建立时间、缓冲时间
  12. 五款最佳Linux下载管理器推荐
  13. 跑步适合戴哪种耳机不掉?专业跑步耳机推荐
  14. EF Core 5.0原生sql语句执行
  15. opencv中findContours 和drawContours画图函数
  16. 【MySQL】启动、数据库/数据表 创建/查看/删除
  17. TransformAnimation - 一个超简单的导航转换动画
  18. 宝塔面板配置及部署javaweb教程(全网最全)
  19. 下载并使用ffmpeg进行音频转换、音频拼接、音视频分离、音视频合成
  20. costmap_2d详解3:costmap_2d_ros.cpp

热门文章

  1. python是不是特别垃圾-Python 这语言真是混乱和原始
  2. python爬虫新手项目-33个Python爬虫项目实战(推荐)
  3. Pytorch用tensorboarX查看损失图打不开
  4. Java 8为什么会移除APT以及mirror API?
  5. UVa133 - The Dole Queue
  6. valgrind的使用
  7. 网络编程学习笔记(shutdown函数)
  8. Django 的模板语法之过滤器
  9. linux-压缩与解压缩(gz,zip,tar,jar,war)
  10. Java构造和解析Json数据的两种方法详解一