JAVA的HTTP请求封装,get详细,post简单,如果想把post细化一下,照着get就可以了

虽然我封装的不如大神们封装的好,但是也是留着自己看吧,准备 以后再重新封装,现在的代码逻辑还是不如大神们厉害,这个也是参考了别人的代码,但是基本上已经是好多都是自己写的了,而且出处也忘记了,如有雷同,敬请原谅。

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HttpRequests {
        /**
         * 是否打印调试信息
         * */
        private static boolean _isDebug=false;
        
        /**
         * 单例
         * **/
        private HttpRequests(){ }
        
        /**
         * @param is(boolean) 设置是否打印调试信息
         * **/
        public static boolean setDebug(boolean is){
                _isDebug=is;
                return _isDebug;
        }

        /**
         * @param is(boolean) 设置是否打印调试信息
         * **/
        public static boolean getDebug(){
                return _isDebug;
        }
        /**
         * @param url(String) have no header
         * **/
        public static String get(String url){
                String result="";
                Map m=new HashMap();
                result=get(url,m);
                return result;
        }
        

        
        /**
         * @param host  input host(String)
         * @param path input path(String)
         * @param parameter input paramter(Map)
         * @param header input header(Map)
         * **/
        public static String get(String host,String path,Map parameter,Map header){
                String result="";
                String url=getURL(host,path,parameter);
                result=get(url,header);
                return result;
        }
        
        /***
         * @param url(String)  url
         * @param header(String[]) 必须是一个key后面接一个value,否则肯定会不准
         * @param header的例子:
         * @param get(url,"Cookies","a=b;c=d","User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)"
         * @param 必须是以上的类似的那种格式才可以,要不然会出错的~
         * */
        public static String get(String url,String ... header){
                String result="";
                Map<String,String> he=new HashMap();
                for(int i=0;i<header.length;i+=2){
                        he.put(header[i-1], header[i]);
                }
                result=get(url,he);
                return result;
        }
        /***
         * @param url(String)  url
         * @param header(Map) 头和cookies 
         * */
        public static String get(String url,Map header){
        //program begining~
                Date pb=new Date();
                String result=null;             
                //创建URL对象
                try {
                        URL des=new URL(url);
                        HttpURLConnection con=(HttpURLConnection)des.openConnection();
                        
                        //写入头信息
                        if(header!=null)        {                               
                                Iterator hi=header.entrySet().iterator();
                                while(hi.hasNext()){
                                        Map.Entry he=(Entry)hi.next();
                                        if(_isDebug){
                                                System.out.println("header\t:\t"+he.getKey()+"\t:\t"+he.getValue());
                                        }
                                        con.setRequestProperty((String)he.getKey(),(String)he.getValue());                                      
                                }                               
                                }
                        //准备连接
                        Date rb=new Date();
                        con.connect();
                        System.out.println(con.getResponseCode()
                                        +"/n"+con.getResponseMessage());
                        //已连接成功
                        Date rg=new Date();
                        
                        //打印返回头         
                        if(_isDebug){
                        Map resheader=con.getHeaderFields();
                        Iterator rh=resheader.entrySet().iterator();
                        while(rh.hasNext()){
                                Map.Entry rhi=(Entry)rh.next();
                                System.out.println("Response Header\t:\t"+rhi.getKey()+"\t:\t"+rhi.getValue());
                        }                       
                        }
                        
                        //返回response的字符串
                        BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
                        String line="";
                        StringBuffer buf=new StringBuffer();
                        while((line=reader.readLine())!=null){
                                buf.append(line);
                        }
                        //关闭读取流,关闭连接
                        reader.close();
                        con.disconnect();
                        Date pd=new Date();
                        if(_isDebug){
                                System.out.println("接口耗时\t:\t"+(rg.getTime()-rb.getTime())+"\tms");
                                System.out.println("程序耗时\t:\t"+(pd.getTime()-pb.getTime())+"\tms");
                        }                       
                        result=buf.toString();
                        
                } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        System.out.println("创建url对象报错~");
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }       
                
                return result;
                
        }
        
        /**
         * @param host(String) host
         * @param path(path) path
         * @param parameter(Map) 参数
         * **/
        public static String getURL(String host,String path,Map parameter){
                String url="http://"+host+path;
                if(_isDebug)
                        System.out.println("url\t+\tpath\t=\t"+url);
                //处理parameter
                StringBuffer pa=new StringBuffer();
                if(parameter!=null){
                        Iterator pi=parameter.entrySet().iterator();
                        while(pi.hasNext()){
                                Map.Entry me=(Entry)pi.next();
                                pa.append(me.getKey()+"="+me.getValue()+"&");
                        }
                        pa.setLength(pa.length()-1);
                        if(_isDebug)
                                System.out.println("parameter\t=\t"+pa.toString());
                }
                url+=pa.toString();
                return url;
        }
        
        
        /**
         * @param type 
         * 分类一
         * @param length
         * **/
        public static String RandString(int type,int length){
                StringBuffer buffer=null;
                StringBuffer sb=null;
                
                return sb.toString();
        }
        /**
         * @param asciicode(String) 把这个字符串中的uincode转换成utf-8的字符串
         * **/
         public static String unicode2String(String asciicode) {
                  
                  String[] asciis = asciicode.split("\\\\u");
              String nativeValue = asciis[0];
              try {
                  for (int i = 1; i < asciis.length; i++) {
                      String code = asciis[i];
                      nativeValue += (char) Integer.parseInt(code.substring(0, 4), 16);
                      if (code.length() > 4) {
                          nativeValue += code.substring(4, code.length());
                      }
                  }
              } catch (NumberFormatException e) {
                  return asciicode;
              }
              return nativeValue;
         }
         
         /**
          * 暂时先不重构post,感觉工作量很大的样子
          * @param url(String) url不用说了
          * @param parameter(Map(String,String) 请求参数
          * @param header(Map(String,String) 请求参数
          * **/
                public static String post(String url,Map<String,String> parameter,Map<String,String> headers){
                        String response="";
                        try {
                                URL des=new URL(url);
                                HttpURLConnection con=(HttpURLConnection)des.openConnection();
                                if(headers!=null)
                                        for(Map.Entry<String,String> map:headers.entrySet()){
                                                con.setRequestProperty(map.getKey(),map.getValue());
                                        }
                                // 设置是否向connection输出,因为这个是post请求,参数要放在  
                                // http正文内,因此需要设为true
                                con.setDoOutput(true);
                                // Read from the connection. Default is true.
                                con.setDoInput(true);
                                // Set the post method. Default is GET 
                                con.setRequestMethod("POST");
                                // Post 请求不能使用缓存
                                con.setUseCaches(false);
                                // URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。  
                                // connection.setFollowRedirects(true);  
                                con.setInstanceFollowRedirects(true);
                                // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数  
                                // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的  
                                // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode  
                                // 进行编码  
                                con.setRequestProperty("Content-Type",  
                                                "application/x-www-form-urlencoded");
                                con.connect();
                                DataOutputStream out=new DataOutputStream(con.getOutputStream());
                            String content="";
                            int i=0;
                            for(Map.Entry<String,String> map:parameter.entrySet()){
                                        if(i!=0)
                                content+="&"+map.getKey()+"="+map.getValue();
                                        else content+=map.getKey()+"="+map.getValue();
                                        ++i;
                                }
                            content=URLEncoder.encode(content,"utf-8");
                            out.writeBytes(content);
                            out.flush();
                            out.close();
                            BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
                                String line="";
                                StringBuffer buf=new StringBuffer();
                                while((line=reader.readLine())!=null){
                                        buf.append(line);
                                }
                                response=buf.toString();
                                reader.close();
                                con.disconnect();
                        } catch (MalformedURLException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        
                        return response;
                }


}