Http连接封装

public enum HttpApi implements IHttpApi {

        INSTANCE;
        // private static final String CLIENT_VERSION_HEADER = "User-Agent";
        private static final int TIMEOUT = 10;
        private DefaultHttpClient mHttpClient;

        // private String mClientVersion; // header

        private HttpApi() {
                mHttpClient = createHttpClient();
        }

        public static HttpApi getInstance() {
                return INSTANCE;
        }

        public String doHttpRequest(HttpRequestBase httpRequest)
                        throws ParseException, IOException {
                HttpResponse response = executeHttpRequest(httpRequest);

                int statusCode = response.getStatusLine().getStatusCode();
                switch (statusCode) {
                case 200:
                        InputStream is = response.getEntity().getContent();
                        try {
                                return convertStreamToString(is);
                        } finally {
                                is.close();
                        }

                case 401:
                        response.getEntity().consumeContent(); // 关闭 释放这个连接
                        throw new ParseException(response.getStatusLine().toString());

                case 404:
                        response.getEntity().consumeContent();
                        throw new ParseException(response.getStatusLine().toString());

                case 500:
                        response.getEntity().consumeContent();
                        throw new ParseException("Foursquare is down. Try again later.");

                default:
                        response.getEntity().consumeContent();
                        throw new ParseException("Error connecting to Foursquare: "
                                        + statusCode + ". Try again later.");
                }
        }

        @Override
        public String doHttpPost(String url, NameValuePair... nameValuePairs)
                        throws IOException, ParseException {
                HttpPost httpPost = createHttpPost(url, nameValuePairs);
                HttpResponse response = executeHttpRequest(httpPost);
                switch (response.getStatusLine().getStatusCode()) {
                case 200:
                        try {
                                return EntityUtils.toString(response.getEntity());
                        } catch (ParseException e) {
                                throw new ParseException(e.getMessage());
                        }
                case 401:
                        response.getEntity().consumeContent();
                        throw new ParseException(response.getStatusLine().toString());

                case 404:
                        response.getEntity().consumeContent();
                        throw new ParseException(response.getStatusLine().toString());
                default:
                        response.getEntity().consumeContent();
                        throw new ParseException(response.getStatusLine().toString());
                }
        }

        @Override
        public String doHttpGet(String url, NameValuePair... nameValuePairs)
                        throws IOException, ParseException {
                HttpGet httpGet = creatHttpGet(url, nameValuePairs);
                HttpResponse response = executeHttpRequest(httpGet);
                switch (response.getStatusLine().getStatusCode()) {
                case 200:
                        try {
                                return EntityUtils.toString(response.getEntity());
                        } catch (ParseException e) {
                                throw new ParseException(e.getMessage());
                        }
                case 401:
                        response.getEntity().consumeContent();
                        throw new ParseException(response.getStatusLine().toString());

                case 404:
                        response.getEntity().consumeContent();
                        throw new ParseException(response.getStatusLine().toString());
                default:
                        response.getEntity().consumeContent();
                        throw new ParseException(response.getStatusLine().toString());
                }
        }

        public HttpResponse executeHttpRequest(HttpRequestBase httpRequest)
                        throws IOException {
                mHttpClient.getConnectionManager().closeExpiredConnections();
                try {
                        return mHttpClient.execute(httpRequest);
                } catch (IOException e) {
                        httpRequest.abort();
                        throw e;
                }
        }

        @Override
        public HttpGet creatHttpGet(String url, NameValuePair... nameValuePairs) {
                String qurey = URLEncodedUtils.format(stripNulls(nameValuePairs),
                                HTTP.UTF_8);
                HttpGet httpGet = new HttpGet(url + "?" + qurey);
                // httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion);
                return httpGet;
        }

        @Override
        public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs) {
                HttpPost httpPost = new HttpPost(url);
                // httpPost.addHeader(CLIENT_VERSION_HEADER, mClientVersion);
                try {
                        httpPost.setEntity(new UrlEncodedFormEntity(
                                        stripNulls(nameValuePairs), HTTP.UTF_8));
                } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                }
                return httpPost;
        }

        public static final String BOUNDARY = "c9152e99a2d6487fb0bfd02adec3aa16";

        public String httpUpload(String urlString,
                        LinkedHashMap<String, String> params, File file, String filetype)
                        throws MalformedURLException, IOException {
                // String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
                String endLine = "\r\n";

                OutputStream os;
                HttpURLConnection conn = (HttpURLConnection) new URL(urlString)
                                .openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="
                                + BOUNDARY);
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Cache-Control", "no-cache");
                conn.connect();
                os = new BufferedOutputStream(conn.getOutputStream());
                os.write(("--" + BOUNDARY + endLine).getBytes());
                os.write((encodePostBody(params, BOUNDARY)).getBytes());
                os.write((endLine + "--" + BOUNDARY + endLine).getBytes());

                // write file
                if (file != null && file.exists()) {
                        try {
                                os.write(("Content-Disposition: form-data; name=\"pic\"; filename=\""
                                                + file.getName() + "\"" + endLine).getBytes());
                                os.write(("Content-Type: " + filetype + endLine + endLine)
                                                .getBytes());
                                FileInputStream fis = new FileInputStream(file);
                                byte[] buffer = new byte[1024 * 50];
                                int flag = -1;
                                while ((flag = fis.read(buffer)) != -1) {
                                        os.write(buffer, 0, flag);
                                }
                        } catch (IOException e) {
                                throw e;
                        }
                }
                os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                os.flush();
                String response = "";
                try {
                        response = convertStreamToString(conn.getInputStream());
                } catch (FileNotFoundException e) {
                        // Error Stream contains JSON that we can parse to a FB error
                        response = convertStreamToString(conn.getErrorStream());
                }
                return response;
        }

        public void shutdownHttpClient() {
                if (mHttpClient != null && mHttpClient.getConnectionManager() != null) {
                        mHttpClient.getConnectionManager().shutdown();
                }
        }

        /**
         * Create a thread-safe client. This client does not do redirecting, to
         * allow us to capture correct "error" codes.
         * 
         *  @return  HttpClient
         */
        private DefaultHttpClient createHttpClient() {

                final HttpParams httpParams = createHttpParams();

                // // 设置最大连接数
                // ConnManagerParams.setMaxTotalConnections(httpParams,
                // MAX_TOTAL_CONNECTIONS);
                // // 设置获取连接的最大等待时间
                // ConnManagerParams.setTimeout(httpParams, WAIT_TIMEOUT);
                // // 设置每个路由最大连接数
                // ConnPerRouteBean connPerRoute = new ConnPerRouteBean(
                // MAX_ROUTE_CONNECTIONS);
                // ConnManagerParams.setMaxConnectionsPerRoute(httpParams,
                // connPerRoute);

                HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
                // 设置我们的HttpClient支持HTTP和HTTPS两种模式
                final SchemeRegistry supportedSchemes = new SchemeRegistry();
                supportedSchemes.register(new Scheme("http", PlainSocketFactory
                                .getSocketFactory(), 80));
                supportedSchemes.register(new Scheme("https", PlainSocketFactory
                                .getSocketFactory(), 443));

                // 设置重定向,缺省为 true
                HttpClientParams.setRedirecting(httpParams, false);
                // 使用线程安全的连接管理来创建HttpClient
                final ClientConnectionManager ccm = new ThreadSafeClientConnManager(
                                httpParams, supportedSchemes);
                return new DefaultHttpClient(ccm, httpParams);
        }

        private HttpParams createHttpParams() {
                final HttpParams params = new BasicHttpParams();
                // Turn off stale checking. Our connections break all the time anyway,
                // and it's not worth it to pay the penalty of checking every time.
                HttpConnectionParams.setStaleCheckingEnabled(params, false);

                HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); // 设置请求超时10秒钟
                HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000); // 设置等待数据超时时间10秒钟
                HttpConnectionParams.setSocketBufferSize(params, 8192);
                return params;
        }

        /**
         * 删除空的NameValuePair
         * 
         * @param nameValuePairs
         * @return
         */
        private List<NameValuePair> stripNulls(NameValuePair... nameValuePairs) {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                for (int i = 0; i < nameValuePairs.length; i++) {
                        NameValuePair param = nameValuePairs ;
                        if (param.getValue() != null) {
                                params.add(param);
                        }
                }
                return params;
        }

        private String convertStreamToString(InputStream is) {

                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();

                String line = null;
                try {
                        while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                        }
                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        try {
                                is.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }

                return sb.toString();
        }

        private static String encodePostBody(
                        LinkedHashMap<String, String> parameters, String boundary) {
                if (parameters == null)
                        return "";
                StringBuilder sb = new StringBuilder();

                for (String key : parameters.keySet()) {
                        Object parameter = parameters.get(key);
                        if (!(parameter instanceof String)) {
                                continue;
                        }
                        sb.append("Content-Disposition: form-data; name=\"" + key
                                        + "\"\r\n\r\n" + (String) parameter);
                        sb.append("\r\n" + "--" + boundary + "\r\n");
                }
                return sb.toString();
        }

        @Override
        public String doHttpPostV2(String urlString,
                        NameValuePair... nameValuePairs) throws IOException, ParseException {
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setUseCaches(false);
                conn.setInstanceFollowRedirects(false);
                conn.setRequestProperty("Content-Type",
                                "application/x-www-form-urlencoded");
                conn.connect();
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                String qurey = URLEncodedUtils.format(stripNulls(nameValuePairs),
                                HTTP.UTF_8);
                out.writeBytes(qurey);
                out.flush();
                out.close();
                String response = "";
                switch (conn.getResponseCode()) {
                case 200:
                        InputStream is = conn.getInputStream();
                        response = convertStreamToString(is);
                default:
                }
                conn.disconnect();
                return response;
        }

        @Override
        public String doHttpGetV2(String urlString, NameValuePair... nameValuePairs)
                        throws IOException, ParseException {
                String qurey = URLEncodedUtils.format(stripNulls(nameValuePairs),
                                HTTP.UTF_8);
                String qureyUrl = urlString + "?" + qurey;
                URL url = new URL(qureyUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(TIMEOUT * 1000);
//                conn.setReadTimeout(TIMEOUT * 1000);
                String response = "";
                switch (conn.getResponseCode()) {
                case 200:
                        InputStream is = conn.getInputStream();
                        response = convertStreamToString(is);
                default:
                }

                conn.disconnect();
                return response;

        }

}



public interface IHttpApi {

        /**
         * doHttpRequest
         * 
         * @param httpRequest
         *            httpGet or httpPost
         * @return
         * @throws ParseException
         * @throws IOException
         */
        String doHttpRequest(HttpRequestBase httpRequest) throws ParseException,
                        IOException;

        /**
         * doHttpPost
         * 
         * @param url
         * @param nameValuePairs
         * @return
         * @throws IOException
         * @throws ParseException
         */
        String doHttpPost(String url, NameValuePair... nameValuePairs)
                        throws IOException, ParseException;

        String doHttpPostV2(String url, NameValuePair... nameValuePairs)
                        throws IOException, ParseException;

        /**
         * doHttpGet
         * 
         * @param url
         * @param nameValuePairs
         * @return
         * @throws IOException
         * @throws ParseException
         */
        String doHttpGet(String url, NameValuePair... nameValuePairs)
                        throws IOException, ParseException;

        String doHttpGetV2(String url, NameValuePair... nameValuePairs)
                        throws IOException, ParseException;

        /**
         * creatHttpGet
         * 
         * @param url
         * @param nameValuePairs
         * @return
         */
        HttpGet creatHttpGet(String url, NameValuePair... nameValuePairs);

        /**
         * createHttpPost
         * 
         * @param url
         * @param nameValuePairs
         * @return
         */
        HttpPost createHttpPost(String url, NameValuePair... nameValuePairs);

        /**
         * httpUpload
         * 
         * @param urlString
         * @param params
         * @param file
         * @param filetype
         * @return
         * @throws MalformedURLException
         * @throws IOException
         */
        String httpUpload(String urlString, LinkedHashMap<String, String> params,
                        File file, String filetype) throws MalformedURLException,
                        IOException;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值