网络连接底层工具类,执行get和post请求(用于在一个项目中去对另外项目发出请求)

import java.io.BufferedReader;
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.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.activation.MimetypesFileTypeMap;


/**
 * 网络连接底层类,执行get和post请求
 * @author Shine_MuShi
 */
public abstract class WebUtils {

        private static final String DEFAULT_CHARSET ="utf-8";
        private static final String METHOD_POST = "POST";
        private static final String METHOD_GET = "GET";
        private static final String USER_AGENT="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.29 Safari/525.13";
        private static final String CTYPE = "application/x-www-form-urlencoded;text/html;charset=" + DEFAULT_CHARSET;
        
        public WebUtils() {
                
        }
        /**
         * 执行POST提交
         * @parmaַ
         * @param params
         * @return
         * @throws IOException
         */
        public static String doPost(String url, Map<String, String> params,int connectTimeout,int readTimeout) throws IOException {
                String query=buildQuery(params, DEFAULT_CHARSET);
                byte[] content=null;
                if(query!=null){
                        content=query.getBytes(DEFAULT_CHARSET);
                }
                return doPost(url, CTYPE, content, connectTimeout, readTimeout);
        }
        
        /**
         * 执行POST提交
         * @param url
         * @param ctype
         * @param content
         * @param connectTimeout
         * @param readTimeout
         * @return
         * @throws IOException
         */
        public static String doPost(String url, String ctype, byte[] content,int connectTimeout,int readTimeout) throws IOException {
                HttpURLConnection conn = null;
                OutputStream out = null;
                String rsp = null;
                try {
                        try{
                                conn = getConnection(new URL(url), METHOD_POST, ctype); 
                                conn.setConnectTimeout(connectTimeout);
                                conn.setReadTimeout(readTimeout);
                                out = conn.getOutputStream();
                                out.write(content);
                                rsp = getResponseAsString(conn);
                        }catch(IOException e){
                                throw e;
                        }
                }finally {
                        if (out != null) {
                                out.close();
                        }
                        if (conn != null) {
                                conn.disconnect();
                        }
                }
                return rsp;
        }
        
        /**
         * 执行GET提交
         * @param url
         * @return
         * @throws IOException
         */
        public static String doGet(String url) throws IOException {
                return doGet(url, DEFAULT_CHARSET);
        }

        public static String doGet(String url, String charset)
                        throws IOException {
                HttpURLConnection conn = null;
                String rsp = null;
                try {
                        try{
                                conn = getConnection(new URL(url), METHOD_GET, CTYPE);
                                rsp = getResponseAsString(conn);
                        }catch(IOException e){
                                throw e;
                        }
                } finally {
                        if (conn != null) {
                                conn.disconnect();
                        }
                }
                return rsp;
        }
        
        /**
         * 获取URL连接
         * @param url
         * @param action
         * @param ctype
         * @return
         * @throws IOException
         */
        private static HttpURLConnection getConnection(URL url, String action, String ctype)
                        throws IOException {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod(action);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");
                conn.setRequestProperty("User-Agent", USER_AGENT);
                conn.setRequestProperty("Content-Type", ctype);
                return conn;
        }
        
        /**
         * 响应流转为String
         * @param conn
         * @return
         * @throws IOException
         */
        private static String getResponseAsString(HttpURLConnection conn) throws IOException {
                String charset = getResponseCharset(conn.getContentType());
                InputStream es = conn.getErrorStream();
                if (es == null) {
                        return getStreamAsString(conn.getInputStream(), charset);
                }
                return null;
        }
        
        /**
         * 从流获取字符串
         * @param stream
         * @param charset
         * @return
         * @throws IOException
         */
        private static String getStreamAsString(InputStream stream, String charset) throws IOException {
                try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
                        StringWriter writer = new StringWriter();
                        char[] chars = new char[256];
                        int count = 0;
                        while ((count = reader.read(chars)) > 0) {
                                writer.write(chars, 0, count);
                        }
                        return writer.toString();
                } finally {
                        if (stream != null) {
                                stream.close();
                        }
                }
        }

        /**
         * 获取响应的字符编码
         * @param ctype
         * @return
         */
        private static String getResponseCharset(String ctype) {
                String charset = DEFAULT_CHARSET;
                if (ctype!=null) {
                        String[] params = ctype.split(";");
                        for (String param : params) {
                                param = param.trim();
                                if (param.startsWith("charset")) {
                                        String[] pair = param.split("=", 2);
                                        if (pair.length == 2) {
                                                if (pair[1]!=null) {
                                                        charset = pair[1].trim();
                                                }
                                        }
                                        break;
                                }
                        }
                }
                return charset;
        }
        
        /**
         * 绑定参数
         * @param params
         * @param charset
         * @return
         * @throws IOException
         */
        public static String buildQuery(Map<String, String> params, String charset) throws IOException {
                if (params == null || params.isEmpty()) {
                        return null;
                }
                StringBuilder query = new StringBuilder();
                Set<Entry<String, String>> entries = params.entrySet();
                boolean hasParam = false;
                for (Entry<String, String> entry : entries) {
                        String name = entry.getKey();
                        String value = entry.getValue();
                        if (name!=null&&value!=null) {
                                if (hasParam) {
                                        query.append("&");
                                } else {
                                        hasParam = true;
                                }
                                query.append(name).append("=").append(URLEncoder.encode(value, charset));
                        }
                }
                return query.toString();
        }
        public static InputStream getStream(String url) throws IOException{
        	HttpURLConnection conn = null;
        	InputStream in = null;
        	try {
        		 conn = getConnection(new URL(url), METHOD_GET, "application/octet-stream");
        		 conn.setConnectTimeout(0);
                 conn.setReadTimeout(0);
                 in = conn.getInputStream();
                 return in;
			} catch (Exception e) {
				System.out.println("出现异常");
				return null;
			}
        }
        /**
         * 
          * @Description
          * @param @param urlStr URL连接地址
          * @param @param textMap 文件其他参数
          * @param @param fileMap 文件流相关数据
          * @param @return
         * @throws IOException 
         * @throws    
          * @return
         */
        public static String formUpload(String urlStr, Map<String, String> textMap,  
                Map<String, String> fileMap) throws IOException {  
            String res = "";  
            HttpURLConnection conn = null;  
            String BOUNDARY = "---------------------------pengliuUloadImage"; //boundary就是request头和上传文件内容的分隔符  
                URL url = new URL(urlStr);  
                conn = (HttpURLConnection) url.openConnection();  
                conn.setConnectTimeout(0);  
                conn.setReadTimeout(0);  
                conn.setDoOutput(true);  
                conn.setDoInput(true);  
                conn.setUseCaches(false);  
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection","Keep-Alive");
                conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
                conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);  
                OutputStream out = new DataOutputStream(conn.getOutputStream());
                // text  
                if (textMap != null) {
                    StringBuffer strBuf = new StringBuffer();  
                    Iterator iter = textMap.entrySet().iterator();  
                    while (iter.hasNext()) {  
                        Map.Entry entry = (Map.Entry) iter.next();  
                        String inputName = (String) entry.getKey();  
                        String inputValue = (String) entry.getValue();  
                        if (inputValue == null) {  
                            continue;  
                        }  
                        strBuf.append("\r\n").append("--").append(BOUNDARY).append(  
                                "\r\n");  
                        strBuf.append("Content-Disposition: form-data; name=\""  
                                + inputName + "\"\r\n\r\n");
                        strBuf.append(inputValue);  
                    }  
                    out.write(strBuf.toString().getBytes());
                }
                // file  
                if (fileMap != null) {  
                    Iterator iter = fileMap.entrySet().iterator();  
                    while (iter.hasNext()) {  
                        Map.Entry entry = (Map.Entry) iter.next();  
                        String inputName = (String) entry.getKey();  
                        String inputValue = (String) entry.getValue();  
                        if (inputValue == null) {  
                            continue;  
                        }  
                        File file = new File(inputValue);  
                        String filename = file.getName();  
                        String contentType = new MimetypesFileTypeMap()  
                                .getContentType(file);  
                        if (filename.endsWith(".png")) {  
                            contentType = "image/png";  
                        }  
                        if (contentType == null || contentType.equals("")) {  
                            contentType = "multipart/form-data";  
                        }  
      
                        StringBuffer strBuf = new StringBuffer();  
                        strBuf.append("\r\n").append("--").append(BOUNDARY).append(  
                                "\r\n");  
                        strBuf.append("Content-Disposition: form-data; name=\""  
                                + inputName + "\"; filename=\"" + filename  
                                + "\"\r\n");  
                        strBuf.append("Content-Type:" + contentType + "\r\n\r\n");  
      
                        out.write(strBuf.toString().getBytes());  
      
                        DataInputStream in = new DataInputStream(  
                                new FileInputStream(file));  
                        int bytes = 0;  
                        byte[] bufferOut = new byte[1024];  
                        while ((bytes = in.read(bufferOut)) != -1) {  
                            out.write(bufferOut, 0, bytes);  
                        }  
                        in.close();  
                    }  
                }  
      
                byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
                out.write(endData);  
                out.flush();  
                out.close();  
      
                // 读取返回数据  
                /*
                StringBuffer strBuf = new StringBuffer();  
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
                String line = null;  
                while ((line = reader.readLine()) != null) {  
                    strBuf.append(line).append("\n");  
                }  
                res = strBuf.toString();  
                reader.close();  
                reader = null;  
                */
                out = conn.getOutputStream();
                String result=getResponseAsString(conn);
                if (conn != null) {  
                    conn.disconnect();  
                    conn = null;  
                } 
                return result;
                 
        }
}
调用api方式:
<pre name="code" class="java"><span style="white-space:pre">					</span>String path=SysconfigHelper.getProperty("pcVisited_baseUrl")+"action2/hsp-SaveHospitalCount.action";
					Map<String,String> params = new HashMap<String, String>();
					params.put("id",request.getParameter("id"));
					WebUtils.doPost(path, params, 0, 0);


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值