package com.dispatcher.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.zip.GZIPInputStream;

import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
public class HttpUtil {
    public static String muip;
    public static String mu;
    public static String ip;
    public static int port;
    public static String realPath;
    static final String COOKIES_HEADER = "Set-Cookie";
    protected static CookieManager msCookieManager = new CookieManager();
    static{
        CookieHandler.setDefault(msCookieManager);
    }
    public static String doGet(String urlStr, Map<String, String> params) throws Exception {
        HttpURLConnection urlConnection=null;
        String result="";
        try {
            // 根据地址创建URL对象
            StringBuffer strUrl=null;
            if(urlStr.startsWith("http://")){
                strUrl= new StringBuffer(urlStr);
            }else{
                strUrl= new StringBuffer("http://" + ip + ":" + port + "/");
                strUrl.append(urlStr);
            }
            if(params!=null){
                // 传递的数据
                strUrl.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    strUrl.append(entry.getKey()+"="+URLEncoder.encode(entry.getValue(),"UTF-8")+"&");
                }
                strUrl.deleteCharAt(strUrl.length()-1);
            }
            URL url = new URL(strUrl.toString());
            // 根据URL对象打开链接
            urlConnection = (HttpURLConnection) url
                    .openConnection();
            if(urlConnection==null){
                return "0";
            }
            // 设置请求的方式
            urlConnection.setRequestMethod("GET");
            if (msCookieManager.getCookieStore().getCookies().size() > 0) {
                urlConnection.setRequestProperty("Cookie",TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));    
            }
            urlConnection.setUseCaches(true);
            // 设置请求的超时时间
            urlConnection.setReadTimeout(18000);
            urlConnection.setConnectTimeout(18000);
            // 设置请求的头
            urlConnection.setRequestProperty("Connection", "keep-alive");
            urlConnection.setRequestProperty("Charset", "utf-8");
            urlConnection.setRequestProperty("Accept-Charset", "UTF-8;");
            urlConnection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            urlConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); 
            // 设置请求的头
            urlConnection
                    .setRequestProperty("User-Agent",
                            "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");
            urlConnection.setDoOutput(false); 
            urlConnection.setDoInput(true); 
            
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                // 获取响应的输入流对象
                Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
                List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
                if (cookiesHeader != null) {
                    for (String cookie : cookiesHeader) {
                        HttpCookie httpCookie=HttpCookie.parse(cookie).get(0);
                        if(!httpCookie.hasExpired()){
                            msCookieManager.getCookieStore().add(null,httpCookie);
                        }else{
                            return "4";
                        }
                    }               
                }
                String encoding = urlConnection.getContentEncoding();
                BufferedInputStream bis=new BufferedInputStream(urlConnection.getInputStream());
                if(encoding!=null&&encoding.contains("gzip")){
                    bis = new BufferedInputStream(new GZIPInputStream(urlConnection.getInputStream()));
                }
                // 创建字节输出流对象
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                // 定义读取的长度
                int len = 0;
                // 定义缓冲区
                byte buffer[] = new byte[1024];
                // 按照缓冲区的大小,循环读取
                while ((len = bis.read(buffer)) != -1) {
                    // 根据读取的长度写入到os对象中
                    baos.write(buffer, 0, len);
                }
                // 释放资源
                bis.close();
                baos.close();
                // 返回字符串
                result = new String(baos.toByteArray());
                
            } else {
                result="0";
            }
        }catch(Exception e){
            e.printStackTrace();
            result="0";
        }finally {
            if(urlConnection!=null){
                urlConnection.disconnect();
            }
        }
        return result;
    }
    public static String doPost(String urlStr, ContentValues params){
        HttpURLConnection urlConnection=null;
        String result="";
        try {
            // 根据地址创建URL对象
            StringBuffer strUrl = new StringBuffer("http://" + ip + ":" + port + "/");
            strUrl.append(urlStr);
            URL url = new URL(strUrl.toString());
            // 根据URL对象打开链接
            urlConnection = (HttpURLConnection) url
                    .openConnection();
            if(urlConnection==null){
                return "0";
            }
            // 设置请求的方式
            urlConnection.setRequestMethod("POST");
            if (msCookieManager.getCookieStore().getCookies().size() > 0) {
                urlConnection.setRequestProperty("Cookie",
                TextUtils.join(";",  msCookieManager.getCookieStore().getCookies()));    
            }
            urlConnection.setUseCaches(false);
            // 设置请求的超时时间
            urlConnection.setReadTimeout(30000);
            urlConnection.setConnectTimeout(30000);
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setDefaultUseCaches(false);
            urlConnection.setAllowUserInteraction(false);
            // 传递的数据
            StringBuffer data=new StringBuffer();
            for (Entry<String, Object> entry : params.valueSet()) {
                data.append(entry.getKey()+"="+URLEncoder.encode(entry.getValue().toString(),"UTF-8")+"&");
            }
            data.deleteCharAt(data.length()-1);
            String content=data.toString();
            // 设置请求的头
            urlConnection.setRequestProperty("Connection", "keep-alive");
            urlConnection.setRequestProperty("Charset", "utf-8");
            urlConnection.setRequestProperty("Accept-Charset", "UTF-8;");
            urlConnection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            urlConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); 
            // 设置请求的头
            urlConnection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 设置请求的头
            urlConnection.setRequestProperty("Content-Length",
                    String.valueOf(content.getBytes().length));
            urlConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            // 设置请求的头
            urlConnection
                    .setRequestProperty("User-Agent",
                            "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0");

            urlConnection.setDoOutput(true);//发送POST请求必须设置允许输出
            urlConnection.setDoInput(true); //发送POST请求必须设置允许输入
                                            //setDoInput的默认值就是true
            urlConnection.connect();
            //获取输出流
            OutputStream os = urlConnection.getOutputStream();
            os.write(content.getBytes());
            os.flush();
            os.close();
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                // 获取响应的输入流对象
                Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
                List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
                if (cookiesHeader != null) {
                    for (String cookie : cookiesHeader) {
                        HttpCookie httpCookie=HttpCookie.parse(cookie).get(0);
                        if(!httpCookie.hasExpired()){
                            msCookieManager.getCookieStore().add(null,httpCookie);
                        }else{
                            return "4";
                        }
                    }               
                }
                String encoding = urlConnection.getContentEncoding();
                BufferedInputStream bis=new BufferedInputStream(urlConnection.getInputStream());
                if(encoding!=null&&encoding.contains("gzip")){
                    bis = new BufferedInputStream(new GZIPInputStream(urlConnection.getInputStream()));
                }
                // 创建字节输出流对象
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                // 定义读取的长度
                int len = 0;
                // 定义缓冲区
                byte buffer[] = new byte[1024];
                // 按照缓冲区的大小,循环读取
                while ((len = bis.read(buffer)) != -1) {
                    // 根据读取的长度写入到os对象中
                    baos.write(buffer, 0, len);
                }
                // 释放资源
                bis.close();
                baos.close();
                // 返回字符串
                result = new String(baos.toByteArray());
                
            } else{
                result="0";
            }
        }catch(Exception e){
            e.printStackTrace();
            result="0";
        }finally {
            if(urlConnection!=null){
                urlConnection.disconnect();
            }
        }
        return result;
    }
    public static String doPost(String urlStr,String fieldName,List<String> fields, ContentValues params){
        HttpURLConnection urlConnection=null;
        String result="";
        try {
            // 根据地址创建URL对象
            StringBuffer strUrl = new StringBuffer("http://" + ip + ":" + port + "/");
            strUrl.append(urlStr);
            URL url = new URL(strUrl.toString());
            // 根据URL对象打开链接
            urlConnection = (HttpURLConnection) url
                    .openConnection();
            if(urlConnection==null){
                return "0";
            }
            // 设置请求的方式
            urlConnection.setRequestMethod("POST");
            if (msCookieManager.getCookieStore().getCookies().size() > 0) {
                urlConnection.setRequestProperty("Cookie",
                TextUtils.join(";",  msCookieManager.getCookieStore().getCookies()));    
            }
            urlConnection.setUseCaches(false);
            urlConnection.setChunkedStreamingMode(0);
            // 设置请求的超时时间
            urlConnection.setReadTimeout(18000);
            urlConnection.setConnectTimeout(18000);
            
            // 设置请求的头
            urlConnection.setRequestProperty("Connection", "keep-alive");
            urlConnection.setRequestProperty("Charset", "utf-8");
            urlConnection.setRequestProperty("Accept-Charset", "UTF-8;");
            urlConnection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            urlConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); 
            // 设置请求的头
            urlConnection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 设置请求的头
            urlConnection
                    .setRequestProperty("User-Agent",
                            "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");
            urlConnection.setDoOutput(true); // 发送POST请求必须设置允许输出
            urlConnection.setDoInput(true); // 发送POST请求必须设置允许输入
                                            //setDoInput的默认值就是true
            //获取输出流
            OutputStream os = urlConnection.getOutputStream();
            // 传递的数据
            DataOutputStream dos = new DataOutputStream(os);
            if(fieldName!=null&&fields!=null){
                for(int i=0;i<fields.size();i++){
                    dos.write((fieldName+"="+URLEncoder.encode(fields.get(i),"utf-8")+"&").getBytes());
                }
            }
            if(params!=null){
                for (Entry<String, Object> entry : params.valueSet()) {
                    dos.write((entry.getKey()+"="+URLEncoder.encode(entry.getValue().toString(),"utf-8")+"&").getBytes());
                }
            }
            dos.flush();
            dos.close();
            os.flush();
            os.close();
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                // 获取响应的输入流对象
                Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
                List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
                if (cookiesHeader != null) {
                    for (String cookie : cookiesHeader) {
                        HttpCookie httpCookie=HttpCookie.parse(cookie).get(0);
                        if(!httpCookie.hasExpired()){
                            msCookieManager.getCookieStore().add(null,httpCookie);
                        }else{
                            return "4";
                        }
                    }               
                }
                String encoding = urlConnection.getContentEncoding();
                BufferedInputStream bis=new BufferedInputStream(urlConnection.getInputStream());
                if(encoding!=null&&encoding.contains("gzip")){
                    bis = new BufferedInputStream(new GZIPInputStream(urlConnection.getInputStream()));
                }
                // 创建字节输出流对象
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                // 定义读取的长度
                int len = 0;
                // 定义缓冲区
                byte buffer[] = new byte[1024];
                // 按照缓冲区的大小,循环读取
                while ((len = bis.read(buffer)) != -1) {
                    // 根据读取的长度写入到os对象中
                    baos.write(buffer, 0, len);
                }
                // 释放资源
                bis.close();
                baos.close();
                // 返回字符串
                result = new String(baos.toByteArray());
            } else {
                result="0";
            }
        }catch(Exception e){
            e.printStackTrace();
            result="0";
        }finally {
            if(urlConnection!=null){
                urlConnection.disconnect();
            }
        }
        return result;
    }
    public static String doPost(String urlStr, Map<String, String> params,String fileParams, File file){
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型
        HttpURLConnection urlConnection=null;
        String result="";
        try {
            StringBuffer strUrl = new StringBuffer("http://" + ip + ":" + port + "/");
            strUrl.append(urlStr);
            URL url = new URL(strUrl.toString());
            urlConnection = (HttpURLConnection) url.openConnection();
            if(urlConnection==null){
                return "0";
            }
            urlConnection.setReadTimeout(18000);
            urlConnection.setConnectTimeout(18000);
            urlConnection.setRequestMethod("POST"); //请求方式
            /*if(sessionId!=null||!"".equals(sessionId)){
                urlConnection.setRequestProperty("Cookie", sessionId);
            }*/
            if (msCookieManager.getCookieStore().getCookies().size() > 0) {
                urlConnection.setRequestProperty("Cookie",
                TextUtils.join(";",  msCookieManager.getCookieStore().getCookies()));    
            }
            urlConnection.setRequestProperty("Charset", "utf-8");//设置编码
            urlConnection.setRequestProperty("Accept-Charset", "UTF-8;");
            urlConnection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            urlConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); 
            urlConnection.setRequestProperty("connection", "keep-alive");
            urlConnection.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            urlConnection.setDoInput(true); //允许输入流
            urlConnection.setDoOutput(true); //允许输出流
            urlConnection.setUseCaches(false); //不允许使用缓存
            urlConnection.setChunkedStreamingMode(0);
            if(file!=null) {
                /** * 当文件不为空,把文件包装并且上传 */
                OutputStream outputSteam=null;
                try{
                    outputSteam=urlConnection.getOutputStream();
                }catch(Exception e){
                    if(urlConnection!=null){
                        urlConnection.disconnect();
                    }
                    return "0";
                }
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(LINE_END);
                if(params!=null){//根据格式,开始拼接文本参数
                    for (Map.Entry<String, String> entry : params.entrySet()) {    
                        sb.append(PREFIX);    
                        sb.append(BOUNDARY);    
                        sb.append(LINE_END);    
                        sb.append("Content-Disposition: form-data; name=\""    
                                + entry.getKey() + "\"" + LINE_END);    
                        sb.append("Content-Type: text/plain; charset=" + "utf-8" + LINE_END);    
                        sb.append("Content-Transfer-Encoding: 8bit" + LINE_END);    
                        sb.append(LINE_END);    
                        sb.append(entry.getValue());    
                        sb.append(LINE_END);    
                    }    
                }
                sb.append(PREFIX);//开始拼接文件参数
                sb.append(BOUNDARY); sb.append(LINE_END);
                /**
                 * 这里重点注意:
                 * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字,包含后缀名的 比如:abc.png
                 */
                sb.append("Content-Disposition: form-data;name=\"" + fileParams  
                        + "\";filename=\"" + file.getName()+"\""+LINE_END);
                sb.append("Content-Type: application/octet-stream; charset="+"utf-8"+LINE_END);
                sb.append(LINE_END);
                //写入文件数据
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                long totalbytes = file.length();
                int len = 0;
                while((len=is.read(bytes))!=-1){
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                dos.close();
                outputSteam.flush();
                outputSteam.close();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功,获取响应的流
                 */
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200) {
                    // 获取响应的输入流对象
                    Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
                    List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
                    if (cookiesHeader != null) {
                        for (String cookie : cookiesHeader) {
                            HttpCookie httpCookie=HttpCookie.parse(cookie).get(0);
                            if(!httpCookie.hasExpired()){
                                msCookieManager.getCookieStore().add(null,httpCookie);
                            }else{
                                return "4";
                            }
                        }               
                    }
                    String encoding = urlConnection.getContentEncoding();
                    BufferedInputStream bis=new BufferedInputStream(urlConnection.getInputStream());
                    if(encoding!=null&&encoding.contains("gzip")){
                        bis = new BufferedInputStream(new GZIPInputStream(urlConnection.getInputStream()));
                    }
                    // 创建字节输出流对象
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    // 定义读取的长度
                    int lenN = 0;
                    // 定义缓冲区
                    byte buffer[] = new byte[1024];
                    // 按照缓冲区的大小,循环读取
                    while ((lenN = bis.read(buffer)) != -1) {
                        // 根据读取的长度写入到os对象中
                        baos.write(buffer, 0, lenN);
                    }
                    // 释放资源
                    bis.close();
                    baos.close();
                    // 返回字符串
                    result = new String(baos.toByteArray());
                    
                } else {
                    result="0";
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            result="0";
        } catch (IOException e) {
            e.printStackTrace();
            result="0";
        }catch (Exception e) {
            e.printStackTrace();
            result="0";
        }finally {
                if(urlConnection!=null){
                urlConnection.disconnect();
            }
        }
        return result;
    }
    public static Bitmap getCodeImage(String path) {
        HttpURLConnection urlConnection=null;
        Bitmap bitmap=null;
        try {
            // 根据地址创建URL对象
            StringBuffer CodeImageUrl = new StringBuffer("http://" + ip + ":" + port);
            if (path != null && !path.equals("")) {
                CodeImageUrl.append("/" + path);
            }
            CodeImageUrl.append("/imgCode?rnd=" + Math.random());
            URL url = new URL(CodeImageUrl.toString());
            // 根据URL对象打开链接
            urlConnection = (HttpURLConnection)   
                    url.openConnection();  
            urlConnection.setRequestMethod("GET");
            urlConnection.setUseCaches(false);
            urlConnection.connect();  
            InputStream is = urlConnection.getInputStream();  
            bitmap = BitmapFactory.decodeStream(is);  
            is.close();  
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if(urlConnection!=null){
                urlConnection.disconnect();
            }
        }
        return bitmap;
    }
}

能解决服务器重端重定向后,返回内容不正确、页面超时等问题


注意:本文归作者所有,未经作者允许,不得转载