htttpUtil--发送http请求的get和post方法

package com.ccb.suap.cloud.facegpups.resource.httpresource;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ccb.suap.cloud.facegpups.controller.FacegpupsController;
import com.ccb.suap.util.log.LogUtil;

import sun.misc.BASE64Decoder;

public class htttpUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(FacegpupsController.class);
    public static String httpPostFrom(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {
        String res = null;
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            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;
                    }
                    String contentType = "image/jpeg";//默认jpg
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + inputName + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    BASE64Decoder decoder = new BASE64Decoder();
                     byte[] bytes = decoder.decodeBuffer(inputValue);
                     out.write(bytes);
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            LOGGER.debug("======"+conn.getResponseCode());
            LOGGER.debug("======"+conn.getResponseMessage());
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = null;
            if(conn.getResponseCode()!=200){
                reader=new BufferedReader(new InputStreamReader(conn.getErrorStream()));    
            }else{
                reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            LOGGER.debug("======"+res);
            reader.close();
            reader = null;
        } catch (Exception e) {
            //LogUtil.error("发送POST请求出错。" + urlStr);
            LOGGER.error("发送POST请求出错。" + urlStr);
            LOGGER.error(e.getMessage(),e);
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
    
    public static String httpPostFrom_data(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {
        String res = null;
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            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;
                    }
                    String contentType = "image/jpeg";//默认jpg
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + inputName + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    BASE64Decoder decoder = new BASE64Decoder();
                     byte[] bytes = decoder.decodeBuffer(inputValue);
                     out.write(bytes);
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            LOGGER.debug("======"+conn.getResponseCode());
            LOGGER.debug("======"+conn.getResponseMessage());
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = null;
            if(conn.getResponseCode()!=200){
                reader=new BufferedReader(new InputStreamReader(conn.getErrorStream()));    
            }else{
                reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            LOGGER.debug("======"+res);
            reader.close();
            reader = null;
        } catch (Exception e) {
            LOGGER.error("发送POST请求出错。" + urlStr+" ,"+e.getMessage(),e);
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
    public static String httpGetFrom(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {
        String res = "";
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            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;
                    }
                    String contentType = "image/jpeg";//默认jpg
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + inputName + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    BASE64Decoder decoder = new BASE64Decoder();
                     byte[] bytes = decoder.decodeBuffer(inputValue);
                     out.write(bytes);
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 读取返回数据
            LOGGER.debug("======"+conn.getResponseCode());
            LOGGER.debug("======"+conn.getResponseMessage());
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = null;
            if(conn.getResponseCode()!=200){
                reader=new BufferedReader(new InputStreamReader(conn.getErrorStream()));    
            }else{
                reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            LOGGER.debug("======"+res);
            reader.close();
            reader = null;
        } catch (Exception e) {
            //LogUtil.error("发送POST请求出错。" + urlStr);
            LOGGER.error("发送POST请求出错。" + urlStr);
            LOGGER.error(e.getMessage(),e);
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
    public static String httpPostFrom(String urlStr, String msg,int connectTimeout1, int soTimeout1, Object dataColl,String path) {
        Map<String, String> textMap=null;
        Map<String, String> fileMap=null;
        if(dataColl != null && dataColl instanceof List){
            List objList = (ArrayList)dataColl;
            textMap = (Map<String, String>) objList.get(0);
            fileMap =  (Map<String, String>)objList.get(1);
        }
        
        if(path!=null){
            urlStr=urlStr+path;
        }
        LogUtil.debug("sendurl:"+urlStr);
        String res = "";
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(connectTimeout1);
            conn.setReadTimeout(soTimeout1);
            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;
                    }
                    String contentType = "image/jpeg";//默认jpg
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + inputName + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    BASE64Decoder decoder = new BASE64Decoder();
                     byte[] bytes = decoder.decodeBuffer(inputValue);
                     out.write(bytes);
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            //读取返回数据
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = null;
            if(conn.getResponseCode()!=200){
                reader=new BufferedReader(new InputStreamReader(conn.getErrorStream()));    
            }else{
                reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            LOGGER.debug("======"+res);
            reader.close();
            reader = null;    
        } catch (Exception e) {
            //LogUtil.error("发送POST请求出错。" + urlStr);
            LOGGER.error("发送POST请求出错。" + urlStr);
            LOGGER.error(e.getMessage(),e);
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
    
    public static String postJson(String urlStr, String msg) {
        String result="";
        HttpURLConnection conn=null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            // 使用 URL 连接进行输出,则将 DoOutput标志设置为 true  
            conn.setDoOutput(true);  
            conn.setRequestMethod("POST");  
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 向服务端发送key = value对
            out.write(msg);
            out.flush();
            out.close();
            // 如果请求响应码是200,则表示成功  
            LOGGER.debug("conn=="+conn);
            BufferedReader in=null;
            if (conn.getResponseCode() == 200) {  
                // HTTP服务端返回的编码是UTF-8,故必须设置为UTF-8,保持编码统一,否则会出现中文乱码  
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            }else
            {
                in=new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); 
            }
             result = in.readLine(); 
             LOGGER.debug("======"+result);
             in.close(); 
            conn.disconnect();// 断开连接  
        } catch (Exception e) {
            //LogUtil.error("发送POST请求出错。" + urlStr);
            LOGGER.error("发送POST请求出错。" + urlStr);
            LOGGER.error(e.getMessage(),e);
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return result;
    }
    
    public static String getCurlData(String urlStr) {
        String resultData = "";
        BufferedReader reader = null;
        HttpURLConnection connection=null;
        try {
            String urlNameString = urlStr;
            URL realUrl = new URL(urlNameString);

            // 打开和URL之间的连接
            connection=(HttpURLConnection)realUrl.openConnection();
            //设置通用的请求属性
            connection.setRequestProperty("accept", "/*");
            connection.setRequestProperty("Connection", "Keep-Alive");
            //connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            connection.connect();
            Map<String,List<String >> map =connection.getHeaderFields();
//            for(String key :map.keySet()){
//                System.out.println(key+"---->"+map.get(key));
//            }
            reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            
            String line;
            while((line=reader.readLine())!=null){
                resultData+=line;
            }
            LOGGER.debug("======"+resultData);
            return resultData;
        } catch (Exception e) {
            LOGGER.error("发送getCurlData请求出错。" + urlStr);
            LOGGER.error(e.getMessage(),e);
        }finally{
            if(reader!=null){
                try{
                    reader.close();
                }catch(IOException e){
                    LOGGER.error("发送getCurlData请求出错。" + urlStr);
                    LOGGER.error(e.getMessage(),e);
                }
            }
            if (connection != null) {
                connection.disconnect();
                connection = null;
            }
        }
        return null;
    }
}
 

发布了91 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/fujianmin19910915/article/details/103574960