《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.
* <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
《IT蓝豹》挑战独立开发项目能力的更多相关文章
- 在android开发中使用multdex的方法-IT蓝豹为你整理
Android系统在安装应用时,往往需要优化Dex,而由于处理工具DexOpt对id数目的限制,导致其处理的数目不能超过65536个,因此在Android开发中,需要使用到MultiDex来解决这个问 ...
- IT蓝豹强烈推荐:符合1-2年工作经验,开发中的难点及相关优化:
IT蓝豹强烈推荐:符合1-2年工作经验,开发中的难点及相关优化: IT蓝豹 ------------------> sqlite数据库版本升级 1.sqlite升级步骤: 1.自己写一个类继承自 ...
- Spring Boot可以离开Spring Cloud独立使用开发项目,但是Spring Cloud离不开Spring Boot,属于依赖的关系。
Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务,Spring Cloud是一个基于Spring Boot实现的云应用开发工具:Spr ...
- web前端学习路线(含20个真实web开发项目集合)
目前web前端工程师日均岗位缺口已经超过50000,随着互联网+的深入发展,html5作为前端展示技术,市场人才需求量将呈直线上涨. Web前端工程师的岗位职责是利用HTML.CSS.Java.DOM ...
- 承接 AutoCAD 二次开发 项目
本人有多年的CAD开发经验,独立完成多个CAD二次开发项目.熟悉.net及Asp.net开发技术,和Lisp开发技术. 现在成立了工作室,独立承接CAD二次开发项目.结项后提供源码及开发文档,有需要的 ...
- 一个不错的loading效果--IT蓝豹
一个不错的loading效果 介绍:一个不错的loading加载效果,弹性收缩,效果不错,学习android动画的朋友可以下载来研究研究本例子其实由SeekBar实现,由MetaballView,Me ...
- 第一次正式java web开发项目的总结
去年下半年到现在,因为公司人员流动,也有好几个新进的员工分给我来带领,也有刚从学校出来的,在和他们交流的过程中,不由的想起自己刚刚进入这行的一些感想. 记得自己当初写过一篇总结的,我想这些对于刚出校门 ...
- 跟我开发NSP(网上查询平台):如何选择开发项目
我想通过一个真实的项目开发的全过程,记录一下开发过程的点点滴滴,记录一下过程中的前思后想.这个全过程包括,如何选择项目.如何分析项目.如何组织项目开发.如何设计开发流程.如何设计软件的总体架构.如何建 ...
- 25个最佳最闪亮的Eclipse开发项目
http://blog.csdn.net/howareyoutodayyhz/article/details/8264599 25个最佳最闪亮的Eclipse开发项目 标签: eclipseEclip ...
随机推荐
- E: Unable to correct problems, you have held broken packages 解决方法
在Ubuntu中安装软件的时候经常碰到E: Unable to correct problems, you have held broken packages.的错误,顾名思义是因为某些软件包冲突导致 ...
- 转 listener.log文件过大导致oracle数据库连接非常慢
数据库(31) 最近发现oracle数据库连接非常慢,sqlplus很快,用客户端就很慢,甚至会无响应. 然后服务器内存一下就飙升到了90%,不是表空间占满了,也不是数据库连接数占满了.重启还是一样 ...
- OAF_开发系列24_实现OAF更新记录显示Record History(案例)
20150716 Created By BaoXinjian
- centos7 firewall 防火墙
在部署dubbo-monitor 和dubbo-admin zookeeper时候,外部访问不了部署好的服务,因为端口问题 ,现在把端口操作总结一下 参考: http://www.cnblogs.co ...
- 如何将Debug文件夹下的资源打包成一个EXE文件直接执行
前言:前段时间写了个小程序,想分享给好友看看,可所以资源都放在Debug文件夹下,整个文件夹发给人家这也太……,为了显得稍微专业一点,想把它们打包一个EXE文件执行,因为我见到到这样的程序,直接一个E ...
- Request.ServerVariables
APPL_MD_PATH-->APPL_PHYSICAL_PATH-->C:\Users\TomZhang\Desktop\GAP\后台修改\UMS\UMSSite\AUTH_TYPE-- ...
- Codeforces 732D [二分 ][贪心]
/* 不要低头,不要放弃,不要气馁,不要慌张 题意: n天进行m科考试,每科考试需要a的复习时间,n天每天最多可以考一科.并且指定哪天考哪科. 注意考试那天不能复习. 问最少需要多少天可全部通过考试. ...
- Android 进程通信机制之 AIDL
什么是 AIDL AIDL 全称 Android Interface Definition Language,即 安卓接口描述语言.听起来很深奥,其实它的本质就是生成进程间通信接口的辅助工具.它的存在 ...
- iOS静态分析举例
XCode-> Product -> Analyze 即可进行iOS静态代码分析.静态分析能发现的问题包括以下几种类型: 1.逻辑错误:访问空指针或未初始化的变量等: 2.内存管理错误:如 ...
- 关于C#本质论和CLR via C#中译本,不吐不快
C#本质论和CLR via C#两本好书,周老师可能是俗务缠身,太忙了吧,翻译得只能让人呵呵了. 你要是忙,别接那么多活好不啦. 现在都在说供给侧改革,都在大力提倡工匠精神,我们做技术的,还是踏实点好 ...