Junit模拟http请求

简介: package cn.trasen.tpmc.tca.controller; import javax.net.ssl.*; import java.io.*; import java.net.HttpURLConnection; import java.
package cn.xxx;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by yinx on 2017/9/19 0019.
 */
public class HttpUtils {
    public static final String UTF8 = "utf-8";
    public static final String GBK = "gbk";
    public static final String GB2312 = "gb2312";
    public static final String ISO88591 = "ISO-8859-1";
    public static int READ_TIMEOUT = 30000;
    public static int CONNECT_TIMEOUT = 30000;

    /**
     * post请求数据
     *
     * @param connectURL
     * @param param
     * @param charset
     * @return
     */
    public static String doPost(String connectURL, String param, String charset) {
        byte[] bytes = null;
        ByteArrayOutputStream byteArrayOut = null;
        URL url = null;
        HttpURLConnection httpPost = null;
        OutputStream out = null;
        InputStream in = null;
        try {
            url = new URL(connectURL);
            httpPost = (HttpURLConnection) url.openConnection();
            httpPost.setRequestMethod("POST");
            httpPost.setDoInput(true);
            httpPost.setDoOutput(true);
            httpPost.setUseCaches(false);
            httpPost.setConnectTimeout(CONNECT_TIMEOUT);
            httpPost.setReadTimeout(READ_TIMEOUT);
            httpPost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpPost.connect();
            out = httpPost.getOutputStream();
            out.write(param.getBytes(charset));
            out.flush();
            in = httpPost.getInputStream();
            byteArrayOut = new ByteArrayOutputStream();
            byte[] buf = new byte[512];
            int l = 0;
            while ((l = in.read(buf)) != -1) {
                byteArrayOut.write(buf, 0, l);
            }
            bytes = byteArrayOut.toByteArray();
            return new String(bytes, charset);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(byteArrayOut);
            close(out);
            close(in);
            close(httpPost);
        }
        return null;
    }

    public static String doPostSSL(String connectURL, Map<String, String> params, String charset) throws MalformedURLException, IOException, UnsupportedEncodingException {
        _ignoreSSL();
        return doPost(connectURL, params, charset);
    }

    /**
     * post请求数据
     *
     * @param connectURL
     * @param params
     * @param charset
     * @return
     */
    public static String doPost(String connectURL, Map<String, String> params, String charset) {
        String param = "";
        if (params != null && !params.isEmpty()) {
            StringBuffer paramBuf = new StringBuffer();
            for (Iterator<String> it = params.keySet().iterator(); it.hasNext();) {
                String key = it.next();
                String value = params.get(key);
                paramBuf.append("&").append(key).append("=").append(value);
            }
            param = paramBuf.substring(1);
        }
        System.out.println("post url:" + connectURL);
        System.out.println("post data:" + param);
        byte[] bytes = null;
        ByteArrayOutputStream byteArrayOut = null;
        URL url = null;
        HttpURLConnection httpPost = null;
        OutputStream out = null;
        BufferedInputStream in = null;
        try {
            url = new URL(connectURL);
            httpPost = (HttpURLConnection) url.openConnection();
            httpPost.setRequestMethod("POST");
            httpPost.setDoInput(true);
            httpPost.setDoOutput(true);
            httpPost.setUseCaches(false);
            httpPost.setConnectTimeout(CONNECT_TIMEOUT);
            httpPost.setReadTimeout(READ_TIMEOUT);
            httpPost.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpPost.connect();
            out = httpPost.getOutputStream();
            out.write(param.getBytes(charset));
            out.flush();

            try {
                in = new BufferedInputStream(httpPost.getInputStream());
            } catch (IOException e) {
                in = new BufferedInputStream(httpPost.getErrorStream());
            }

            byteArrayOut = new ByteArrayOutputStream();
            byte[] buf = new byte[512];
            int l = 0;
            while ((l = in.read(buf)) != -1) {
                byteArrayOut.write(buf, 0, l);
            }
            bytes = byteArrayOut.toByteArray();
            return new String(bytes, charset);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(byteArrayOut);
            close(in);
            close(out);
            close(httpPost);
        }
        return null;
    }

    /**
     * Get请求数据
     *
     * @param connectURL
     * @param charset
     * @return
     */
    public static String doGet(String connectURL, String charset) {
        byte[] bytes = null;
        ByteArrayOutputStream byteArrayOut = null;
        URL url = null;
        HttpURLConnection httpGet = null;
        InputStream in = null;
        try {
            url = new URL(connectURL);
            httpGet = (HttpURLConnection) url.openConnection();
            httpGet.setConnectTimeout(CONNECT_TIMEOUT);
            httpGet.setReadTimeout(READ_TIMEOUT);
            httpGet.connect();
            in = httpGet.getInputStream();
            byteArrayOut = new ByteArrayOutputStream();
            byte[] buf = new byte[512];
            int l = 0;
            while ((l = in.read(buf)) != -1) {
                byteArrayOut.write(buf, 0, l);
            }
            bytes = byteArrayOut.toByteArray();
            return bytes != null ? new String(bytes, charset) : null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(byteArrayOut);
            close(in);
            close(httpGet);
        }
        return null;
    }

    private static void close(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
                stream = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void close(HttpURLConnection httpConn){
        if(httpConn != null){
            httpConn.disconnect();
        }
    }

    private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslsession) {
            return true;
        }
    };

    /**
     * 忽略SSL
     */
    private static void _ignoreSSL() {
        try {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } };

            // Install the all-trusting trust manager

            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
        } catch (KeyManagementException ex) {
            Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String doPost(String actionURL, HashMap<String, String> parameters){
        String response = "";
        try{
            URL url = new URL(actionURL);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //发送post请求需要下面两行
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");;
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //设置请求数据内容
            String requestContent = "";
            Set<String> keys = parameters.keySet();
            for(String key : keys){
                requestContent = requestContent + key + "=" + parameters.get(key) + "&";
            }
            requestContent = requestContent.substring(0, requestContent.lastIndexOf("&"));
            DataOutputStream ds = new DataOutputStream(connection.getOutputStream());
            //使用write(requestContent.getBytes())是为了防止中文出现乱码
            ds.write(requestContent.getBytes());
            ds.flush();
            try{
                //获取URL的响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                String s = "";
                String temp = "";
                while((temp = reader.readLine()) != null){
                    s += temp;
                }
                response = s;
                reader.close();
            }catch(IOException e){
                e.printStackTrace();
                System.out.println("No response get!!!");
            }
            ds.close();
        }catch(IOException e){
            e.printStackTrace();
            System.out.println("Request failed!");
        }
        return response;
    }

    /**
     * @author Johnson
     * @method singleFileUploadWithParameters
     * @description 集上传单个文件与传递参数于一体的方法
     * @param actionURL 上传文件的URL地址包括URL
     * @param fileType 文件类型(枚举类型)
     * @param uploadFile 上传文件的路径字符串
     * @param parameters 跟文件一起传输的参数(HashMap)
     * @return String("" if no response get)
     * @attention 上传文件name为file(服务器解析)
     * */
    /*public String singleFileUploadWithParameters(String actionURL, String uploadFile, MIME_FileType fileType, HashMap<String, String> parameters){
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------7e0dd540448";
        String response = "";
        try{
            URL url = new URL(actionURL);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //发送post请求需要下面两行
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //设置请求参数
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            //获取请求内容输出流
            DataOutputStream ds = new DataOutputStream(connection.getOutputStream());
            String fileName = uploadFile.substring(uploadFile.lastIndexOf(this.PathSeparator) + 1);
            //开始写表单格式内容
            //写参数
            Set<String> keys = parameters.keySet();
            for(String key : keys){
                ds.writeBytes(twoHyphens + boundary + end);
                ds.writeBytes("Content-Disposition: form-data; name=\"");
                ds.write(key.getBytes());
                ds.writeBytes("\"" + end);
                ds.writeBytes(end);
                ds.write(parameters.get(key).getBytes());
                ds.writeBytes(end);
            }
            //写文件
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; " + "name=\"file\"; " + "filename=\"");
            //防止中文乱码
            ds.write(fileName.getBytes());
            ds.writeBytes("\"" + end);
            ds.writeBytes("Content-Type: " + fileType.getValue() + end);
            ds.writeBytes(end);
            //根据路径读取文件
            FileInputStream fis = new FileInputStream(uploadFile);
            byte[] buffer = new byte[1024];
            int length = -1;
            while((length = fis.read(buffer)) != -1){
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            fis.close();
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            ds.writeBytes(end);
            ds.flush();
            try{
                //获取URL的响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                String s = "";
                String temp = "";
                while((temp = reader.readLine()) != null){
                    s += temp;
                }
                response = s;
                reader.close();
            }catch(IOException e){
                e.printStackTrace();
                System.out.println("No response get!!!");
            }
            ds.close();
        }catch(IOException e){
            e.printStackTrace();
            System.out.println("Request failed!");
        }
        return response;
    }*/
}
相关文章
|
2月前
|
Rust 前端开发 API
Tauri 开发实践 — Tauri HTTP 请求开发
本文介绍了如何在 Tauri 中发起 HTTP 请求。首先通过安装 Tauri 生态中的工具包并配置 `tauri.conf.json` 文件来允许特定域名的 HTTP 通信。接着封装了一个简单的 HTTP 客户端类,并在页面中使用该客户端实现 GET 和 POST 请求。最后提供了完整的源码地址以供参考。此功能使得桌面应用能够与远程服务器进行交互,增强了应用的实用性。
136 1
Tauri 开发实践 — Tauri HTTP 请求开发
|
12天前
|
JSON Java 数据格式
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
60 25
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
|
11天前
|
Web App开发 大数据 应用服务中间件
什么是 HTTP Range请求(范围请求)
HTTP Range 请求是一种非常有用的 HTTP 功能,允许客户端请求资源的特定部分,从而提高传输效率和用户体验。通过合理使用 Range 请求,可以实现断点续传、视频流播放和按需加载等功能。了解并掌握 HTTP Range 请求的工作原理和应用场景,对开发高效的网络应用至关重要。
47 15
|
15天前
|
数据采集 JSON 测试技术
Grequests,非常 Nice 的 Python 异步 HTTP 请求神器
在Python开发中,处理HTTP请求至关重要。`grequests`库基于`requests`,支持异步请求,通过`gevent`实现并发,提高性能。本文介绍了`grequests`的安装、基本与高级功能,如GET/POST请求、并发控制等,并探讨其在实际项目中的应用。
24 3
|
20天前
|
前端开发 UED 开发者
CSS Sprites和图标字体在网页图标加载优化中的应用。CSS Sprites通过合并多图标减少HTTP请求,提升加载速度
本文探讨了CSS Sprites和图标字体在网页图标加载优化中的应用。CSS Sprites通过合并多图标减少HTTP请求,提升加载速度;图标字体则以字体形式呈现图标,便于调整样式。文章分析了两者的优缺点及应用场景,并提供了应用技巧和注意事项,旨在帮助开发者提升页面性能,改善用户体验。
21 5
|
1月前
|
缓存 前端开发 API
|
2月前
|
数据采集 前端开发 算法
Python Requests 的高级使用技巧:应对复杂 HTTP 请求场景
本文介绍了如何使用 Python 的 `requests` 库应对复杂的 HTTP 请求场景,包括 Spider Trap(蜘蛛陷阱)、SESSION 访问限制和请求频率限制。通过代理、CSS 类链接数控制、多账号切换和限流算法等技术手段,提高爬虫的稳定性和效率,增强在反爬虫环境中的生存能力。文中提供了详细的代码示例,帮助读者掌握这些高级用法。
111 1
Python Requests 的高级使用技巧:应对复杂 HTTP 请求场景
|
1月前
|
JSON API 数据格式
Python中获取HTTP请求响应体的详解
本文介绍了如何使用Python的`requests`和`urllib`库发送HTTP请求并处理响应体。`requests`库简化了HTTP请求过程,适合快速开发;`urllib`库则更为底层,适用于性能要求较高的场景。文章详细演示了发送GET请求、处理JSON响应等常见操作。
44 3
|
29天前
|
安全 API 网络安全
使用OkHttp进行HTTPS请求的Kotlin实现
使用OkHttp进行HTTPS请求的Kotlin实现
|
11天前
|
Web App开发 网络安全 数据安全/隐私保护
Lua中实现HTTP请求的User-Agent自定义
Lua中实现HTTP请求的User-Agent自定义

热门文章

最新文章