Android HttpURLConnection的使用

封装了get post form表单上传文件

public class FetchUrl {

    public static final class FetchUrlException extends Exception {
        private static final long serialVersionUID = -1225796193361530073L;
        private int mCode;
        private String mOrigMsg;

        public static final class CODE {
            public static final int UNSUPPORTED_PARAM_ENCODING = 1;
            public static final int SERVER_ERROR = 2;
            public static final int SERVER_READ_ERROR = 3;
            public static final int CLIENT_PROTOCOL_ERROR = 4;
            public static final int REQUEST_METHOD_NOT_ALLOWED = 5;
            public static final int NO_PEER_CERTIFICATE = 6;
            public static final int INVALID_URL = 7;
            public static final int ILLEGAL_PARAM = 9;
        }

        public FetchUrlException(int code, String origMsg) {
            super("Error Code: " + code);
            mCode = code;
            mOrigMsg = origMsg;
        }

        public int getCode() {
            return mCode;
        }

        public String getMsg() {
            switch (mCode) {
            case CODE.UNSUPPORTED_PARAM_ENCODING:
                return "Unsupported parameter encoding: " + mOrigMsg;
            case CODE.SERVER_ERROR:
                return "Server error: " + mOrigMsg;
            case CODE.SERVER_READ_ERROR:
                return "Server read error: " + mOrigMsg;
            case CODE.CLIENT_PROTOCOL_ERROR:
                return "Client protocol error: " + mOrigMsg;
            case CODE.REQUEST_METHOD_NOT_ALLOWED:
                return "Request method not allowed: " + mOrigMsg;
            case CODE.NO_PEER_CERTIFICATE:
                return "No peer certificate: " + mOrigMsg;
            case CODE.ILLEGAL_PARAM:
                return "Illegal paramters" + mOrigMsg;
            default:
                return "Unknown error: " + mOrigMsg;
            }
        }
    }

    public static final class FetchUrlMethod {
        public static final int GET = 0;
        public static final int POST = 1;
    }

    public static final class FetchUrlResponse {
        public int code;
        public byte[] content;
        public HashMap<String, String> headers;
        public List<String> cookies;
        public HashMap<String, String> cookie_maps;
    }

    protected static final String HEADER_ACCEPT_CHARSET = "Accept-Charset";
    protected static final String DEFAULT_PARAMS_ENCODING = "UTF-8";
    protected static final String POST_STR = "POST";
    protected static final String GET_STR = "GET";
    protected static final String BOUNDARY = "*****";
    protected static final String LINE_FEED = "\r\n";

    public static FetchUrlResponse fetchUrl(int method, String url, HashMap<String, String> headers,
            ArrayList<NameValuePair> data, int connection_timeout, int socket_timeout) throws FetchUrlException {
        return fetchUrl(method, url, headers, data, null, null, connection_timeout, socket_timeout);
    }

    public static FetchUrlResponse fetchUrl(int method, String url, HashMap<String, String> headers,
            ArrayList<NameValuePair> data, ArrayList<NameValuePair> form, Attatchment file, int connection_timeout,
            int socket_timeout) throws FetchUrlException {
        byte[] post_data = null;
        if (method == FetchUrlMethod.POST) {
            if (data != null && data.size() > 0) {
                try {
                    post_data = encodeParameters(data, DEFAULT_PARAMS_ENCODING);
                } catch (UnsupportedEncodingException e) {
                    throw new FetchUrlException(FetchUrlException.CODE.UNSUPPORTED_PARAM_ENCODING, e.getMessage());
                }
            }
        } else if (method == FetchUrlMethod.GET) {
            if (data != null && data.size() > 0) {
                if (url.contains("?")) {
                    throw new FetchUrlException(FetchUrlException.CODE.CLIENT_PROTOCOL_ERROR,
                            "data and query string are exclusive in GET method");
                }
                url = url + "?" + Utils.encodeQs(data);
            }
        } else {
            throw new FetchUrlException(FetchUrlException.CODE.REQUEST_METHOD_NOT_ALLOWED,
                    "" + method + " is not a valid request method");
        }
        return fetchUrlRaw(method, url, headers, post_data, form, file, connection_timeout, socket_timeout);
    }

    private static FetchUrlResponse fetchUrlRaw(int method, String url, HashMap<String, String> headers, byte[] data,
            ArrayList<NameValuePair> form, Attatchment file, int connection_timeout, int socket_timeout)
                    throws FetchUrlException {
        try {
            HttpURLConnection connection = openConnection(url, connection_timeout, socket_timeout);
            if (FetchUrlMethod.GET == method) {
                connection.setRequestMethod(GET_STR);
            } else if (FetchUrlMethod.POST == method) {
                connection.setRequestMethod(POST_STR);
            }

            if (file != null) {
                connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            }

            if (headers != null && headers.size() > 0) {
                for (String headerName : headers.keySet()) {
                    connection.addRequestProperty(headerName, headers.get(headerName));
                }
            }

            DataOutputStream out = null;
            if (data != null) {
                connection.setDoOutput(true);
                out = new DataOutputStream(connection.getOutputStream());
                out.write(data);
                out.flush();
            }
            if (file != null) {
                if (out == null) {
                    connection.setDoOutput(true);
                    out = new DataOutputStream(connection.getOutputStream());
                }
                if (form != null && form.size() > 0) {
                    for (NameValuePair pair : form) {
                        StringBuilder sb = new StringBuilder();
                        sb.append("--" + BOUNDARY).append(LINE_FEED);
                        sb.append("Content-Disposition: form-data; name=\"" + pair.getName() + "\"").append(LINE_FEED);
                        sb.append("Content-Type: text/plain; charset=" + DEFAULT_PARAMS_ENCODING).append(LINE_FEED);
                        sb.append(LINE_FEED);
                        sb.append(pair.getValue()).append(LINE_FEED);
                        out.write(sb.toString().getBytes(DEFAULT_PARAMS_ENCODING));
                    }
                }
                StringBuilder sb = new StringBuilder();
                sb.append("--" + BOUNDARY).append(LINE_FEED);
                sb.append("Content-Disposition: form-data; name=\"" + file.name + "\"; filename=\"" + file.fileName
                        + "\"").append(LINE_FEED);
                sb.append("Content-Type: " + file.contentType).append(LINE_FEED);
                sb.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
                sb.append(LINE_FEED);
                out.write(sb.toString().getBytes(DEFAULT_PARAMS_ENCODING));

                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = file.inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                file.inputStream.close();
                out.write(LINE_FEED.getBytes(DEFAULT_PARAMS_ENCODING));

                String end = "--" + BOUNDARY + LINE_FEED;
                out.write(end.getBytes(DEFAULT_PARAMS_ENCODING));
                out.flush();
                out.close();
            } else if (form != null && form.size() > 0){
                for (NameValuePair pair : form) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("--" + BOUNDARY).append(LINE_FEED);
                    sb.append("Content-Disposition: form-data; name=\"" + pair.getName() + "\"").append(LINE_FEED);
                    sb.append("Content-Type: text/plain; charset=" + DEFAULT_PARAMS_ENCODING).append(LINE_FEED);
                    sb.append(LINE_FEED);
                    sb.append(pair.getValue()).append(LINE_FEED);
                    out.write(sb.toString().getBytes(DEFAULT_PARAMS_ENCODING));
                }
                out.flush();
                out.close();
            }
            if (out != null) {
                out.close();
            }

            FetchUrlResponse response = new FetchUrlResponse();
            response.code = connection.getResponseCode();

            if (response.code == -1) {
                // -1 is returned by getResponseCode() if the response code
                // could not be retrieved.
                // Signal to the caller that something was wrong with the
                // connection.
                throw new IOException("Could not retrieve response code from HttpUrlConnection.");
            }
            InputStream istream;
            try {
                istream = connection.getInputStream();
            } catch (IOException e) {
                istream = connection.getErrorStream();
            }
            if (istream != null) {
                response.content = Utils.inputStreamToByteArray(istream);
            }
            response.headers = new HashMap<String, String>();
            Map<String, List<String>> respHeaders = connection.getHeaderFields();
            response.cookies = respHeaders.get("Set-Cookie");

            response.cookie_maps = new HashMap<String, String>();
            if (response.cookies != null) {
                for (String str : response.cookies) {
                    HttpCookie cookie = HttpCookie.parse(str).get(0);
                    response.cookie_maps.put(cookie.getName(), cookie.getValue());
                }
            }

            for (Map.Entry<String, List<String>> respHeader : respHeaders.entrySet()) {
                response.headers.put(respHeader.getKey(), connection.getHeaderField(respHeader.getKey()));
            }
            return response;

        } catch (SSLException e) {
            throw new FetchUrlException(FetchUrlException.CODE.NO_PEER_CERTIFICATE, e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new FetchUrlException(FetchUrlException.CODE.UNSUPPORTED_PARAM_ENCODING, e.getMessage());
        } catch (ProtocolException e) {
            throw new FetchUrlException(FetchUrlException.CODE.CLIENT_PROTOCOL_ERROR, e.getMessage());
        } catch (IllegalAccessError e) {
            throw new FetchUrlException(FetchUrlException.CODE.SERVER_READ_ERROR, e.getMessage());
        } catch (NullPointerException e) {
            throw new FetchUrlException(FetchUrlException.CODE.ILLEGAL_PARAM, e.getMessage());
        } catch (IOException e) {
            throw new FetchUrlException(FetchUrlException.CODE.SERVER_READ_ERROR, e.getMessage());
        } catch (IllegalStateException e) {
            throw new FetchUrlException(FetchUrlException.CODE.SERVER_ERROR, e.getMessage());
        }
    }

    private static HttpURLConnection openConnection(String url, int connection_timeout, int socket_timeout)
            throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestProperty(HEADER_ACCEPT_CHARSET, DEFAULT_PARAMS_ENCODING);
        connection.setConnectTimeout(connection_timeout);
        connection.setReadTimeout(socket_timeout);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        return connection;
    }

    /**
     * Converts <code>params</code> into an application/x-www-form-urlencoded
     * encoded string.
     */
    private static byte[] encodeParameters(ArrayList<NameValuePair> params, String paramsEncoding)
            throws UnsupportedEncodingException {
        return Utils.encodeQs(params, paramsEncoding).getBytes(paramsEncoding);
    }

    public static String encodeQs(ArrayList<NameValuePair> data) {
        return Utils.encodeQs(data);
    }
}
public class Utils {
    public static String encodeQs(ArrayList<NameValuePair> data) {
        try {
            return encodeQs(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    static String encodeQs(ArrayList<NameValuePair> data, String paramsEncoding) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.size(); i++) {
            NameValuePair kv = data.get(i);
            if (i != 0) {
                sb.append("&");
            }
            sb.append(URLEncoder.encode(kv.getName(), paramsEncoding));
            sb.append("=");
            sb.append(URLEncoder.encode(kv.getValue() == null ? "" : kv.getValue(), paramsEncoding));
        }
        return sb.toString();
    }

    static byte[] inputStreamToByteArray(InputStream is) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int read_count;
        byte[] data = new byte[16384];
        while ((read_count = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, read_count);
        }
        buffer.flush();
        return buffer.toByteArray();
    }

    // TODO always correct?
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {

        }
        return null;
    }

}
时间: 2024-10-07 17:10:01

Android HttpURLConnection的使用的相关文章

Android HttpURLConnection源码分析

Android HttpURLConnection源码分析 之前写过HttpURLConnection与HttpClient的区别及选择.后来又分析了Volley的源码. 最近又遇到了问题,想在Volley中针对HttpURLConnection添加连接池的功能,开始有点懵了,不知道HttpURLConnection要怎么加连接池, 虽然感觉这是没必要的,但是心底确拿不出依据.所以研究下HttpURLConnection的源码进行分析. 在使用的时候都是通过URL.openConnection(

android httpurlconnection

HttpURLConnection是java的标准类,HttpURLConnection继承自URLConnection,可用于向指定网站发送GET.POST请求.除此之外,在Android中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的.最新的.功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议.      GET请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),以?分割URL和传输数据,参数之间以&相连;POS

ANDROID HttpURLConnection,HttpClient和最简单的handler机制

handler机制在Android开发中主要用于主线程和子线程的沟通,子线程发送必要的信息给主线程,然后在主线程中更新ui: package com.example.webview; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import an

android httpurlconnection或者httpclient总是超时,服务器正常,但网络正常,浏览器可以上网

============问题描述============ HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(10000); conn.setRequestMethod("POST"); conn.setRequestProperty("Response-Typ

Android HttpURLConnection POST/GET

//新建线程 new Thread(new Runnable() { public void run() { try { //将path转成Url格式 URL realurl = new URL(path); // 打开和URL之间的连接 HttpURLConnection conn = (HttpURLConnection) realurl.openConnection(); // http正文内,因此需要设为true, 默认情况下是false; conn.setDoOutput(true);

Android --http请求之HttpURLConnection

参考博客:Android HttpURLConnection 基础使用 参考博客:Android访问网络,使用HttpURLConnection还是HttpClient? String getUrl = mUrl + "/login.ashx?type=authen&user=" + mEmail + "&pwd=" + mPassword; URL loginUrl = null; InputStream in = null; HttpURLCon

【Android 面试基础知识点整理】

针对Android面试中常见的一些知识点整理,Max 只是个搬运工,感谢本文中引用文章的各位作者,给大家分享了这么多优秀文章,对于其中的解析,是原作者个人见解,有错误和不准确的地方,也请大家积极指正. 本文将持续更新,同时我也将其放在Github上:Point-of-Android 同时可以看Max的个人博客:海上钢琴师 Android中的异步任务机制 Android中AsyncTak的使用与源码分析 http://blog.csdn.net/bboyfeiyu/article/details/

Android移动端网络优化

介绍下针对移动端的网络优化,不限于 Android,同样适用于 iOS 和 H5 本文为性能优化系列第四篇,目前性能调优专题已完成以下部分: 性能优化总纲——性能问题及性能调优方式 性能优化第四篇——移动网络优化 性能优化第三篇——代码优化 性能优化第二篇——布局优化 性能优化第一篇——数据库性能优化 Android 性能调优工具 TraceView 性能优化实例 一个网络请求可以简单分为连接服务器 -> 获取数据两个部分. 其中连接服务器前还包括 DNS 解析的过程:获取数据后可能会对数据进行

Android面试题集

前几天整理了Java面试题集合,今天再来整理下Android相关的面试题集合.假设你希望能得到最新的消息,能够关注https://github.com/closedevice/interview-about,我会不断的添加和修正相关问题的描写叙述. 基础 谈谈Activity的生命周期 介绍不同场景下Activity生命周期的变化过程 启动Activity: onCreate()->onStart()->onResume(),Activity进入运行状态. Activity退居后台: 当前Ac