溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

  挑戰(zhàn)獨(dú)立開發(fā)項(xiàng)目能力--IT藍(lán)豹

發(fā)布時(shí)間:2020-08-05 22:04:09 來源:網(wǎng)絡(luò) 閱讀:314 作者:楊光成 欄目:移動(dòng)開發(fā)

                     
    做了5年的android開發(fā),今天沒事寫寫剛?cè)胄胁痪玫臅r(shí)候第一次獨(dú)立開發(fā)項(xiàng)目的心得體會(huì),
    當(dāng)時(shí)我剛工作8個(gè)月,由于公司運(yùn)營(yíng)不善倒閉了,在2011年3月份我開始準(zhǔn)備跳槽,
    看了一周android筆試題和面試題后,然后就去找工作,當(dāng)時(shí)去面試的時(shí)候說自己有獨(dú)立項(xiàng)目開發(fā)的經(jīng)驗(yàn)。
    結(jié)果面上了幾家公司,后來選擇一家游戲公司,開始游戲開發(fā)的生涯。當(dāng)時(shí)我去的時(shí)候就android組就我一個(gè)人,
    也沒有人帶領(lǐng),去公司一個(gè)月后公司決定要我把網(wǎng)游游戲移植到手游,那時(shí)候確實(shí)沒有獨(dú)立開發(fā)項(xiàng)目的經(jīng)驗(yàn)。
    但是又只有一個(gè)人做,沒辦法只有自己慢慢研究,那時(shí)候沒有像現(xiàn)在資源多,網(wǎng)上隨便找。
    還是堅(jiān)持慢慢從網(wǎng)絡(luò)框架一步一步開始搭建。當(dāng)時(shí)獨(dú)立做完項(xiàng)目后感覺個(gè)人技術(shù)能力瞬間提高了很多,因?yàn)椴辉谶€怕獨(dú)立承擔(dān)項(xiàng)目了。
    希望我的感受能給同樣剛?cè)胄械呐笥涯芙o與幫助。如今本人自己做一個(gè)技術(shù)網(wǎng)站:IT藍(lán)豹(www.itlanbao.com)
        當(dāng)時(shí)使用的網(wǎng)絡(luò)框架是HttpClient,先實(shí)現(xiàn)ReceiveDataListener接口用來接收數(shù)據(jù)返回,然后設(shè)置如下代碼調(diào)用
        
    調(diào)用方法:
    private void initHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = HttpClientFactory
                    .newInstance(Constants.CONNECTION_TIMEOUT);
            mHttpTransport = new HttpTransport(mHttpClient);
            mHttpTransport.setReceiveDataListener(this);
        }
    }
    
    
網(wǎng)絡(luò)請(qǐng)求代碼部分如下: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 >
     * 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;
    }

    /**
     * 關(guān)閉連接
     */
    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);
    }
}


//最后網(wǎng)絡(luò)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藍(lán)豹:www.itlanbao.com

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI