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

原创 2015年07月08日 11:51:38
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);



            
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

java project 项目的开发--简单的http请求, 模仿浏览器发出请求get

一, 模仿浏览器请求(get方式):       点击项目:右击>>>Build Path >>>Add Library>>>User Library>>>next 出现如下图:...

Java网络请求(get/post)工具类实现的两种方式

基于HttpClient实现基本思路都是一样的,通过HttpResponse实例获得请求返回的数据体,具体数据封装在HttpEntity对象中。 /** * Created by Song on 2...

请求网络连接工具类

判断是否有网络连接import android.content.Context; import android.net.ConnectivityManager; import android.net....

java http请求的get和post方法工具类

public class BaseHttpRequest { /**      * 向指定URL发送GET方法的请求      *       * @param url   ...

post/get请求(http,https)工具类

package cn.knet.data.untils; import java.io.IOException; import java.net.SocketTimeoutException; im...

Apache 大三方法HTTP请求链接响应之HttpClient的GET和POST工具类封装

一、在HttpConnectUtils 定义一个回调接口,并注册接口 /** 第一步定义接口 */ public interface HTTPCallBack { public void re...

Http请求get、post工具类

在网上找了好久都没有找到post、get请求的工具类,现在整理了一下分享出来。http工具类如下:package com.qlwb.business.util;import java.io.Buffe...

java发送http的get、post请求工具类

java发送http的get、post请求工具类

HttpClient4.3 post与get请求工具类完整示例

整个工具类代码如下所示,可直接使用! import java.io.IOException; import org.apache.http.HttpEntity; import org.apache...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)