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;
    }*/
}
相关文章
|
17天前
|
数据采集
Haskell爬虫:连接管理与HTTP请求性能
Haskell爬虫:连接管理与HTTP请求性能
|
24天前
|
JSON 安全 前端开发
类型安全的 Go HTTP 请求
类型安全的 Go HTTP 请求
|
23天前
|
数据采集 JSON API
异步方法与HTTP请求:.NET中提高响应速度的实用技巧
本文探讨了在.NET环境下,如何通过异步方法和HTTP请求提高Web爬虫的响应速度和数据抓取效率。介绍了使用HttpClient结合async和await关键字实现异步HTTP请求,避免阻塞主线程,并通过设置代理IP、user-agent和cookie来优化爬虫性能。提供了代码示例,演示了如何集成这些技术以绕过目标网站的反爬机制,实现高效的数据抓取。最后,通过实例展示了如何应用这些技术获取API的JSON数据,强调了这些方法在提升爬虫性能和可靠性方面的重要性。
异步方法与HTTP请求:.NET中提高响应速度的实用技巧
|
9天前
|
JSON JavaScript 前端开发
Haskell中的数据交换:通过http-conduit发送JSON请求
Haskell中的数据交换:通过http-conduit发送JSON请求
|
11天前
|
JSON API 开发者
Python网络编程新纪元:urllib与requests库,让你的HTTP请求无所不能
【9月更文挑战第9天】随着互联网的发展,网络编程成为现代软件开发的关键部分。Python凭借简洁、易读及强大的特性,在该领域展现出独特魅力。本文介绍了Python标准库中的`urllib`和第三方库`requests`在处理HTTP请求方面的优势。`urllib`虽API底层但功能全面,适用于深入控制HTTP请求;而`requests`则以简洁的API和人性化设计著称,使HTTP请求变得简单高效。两者互补共存,共同推动Python网络编程进入全新纪元,无论初学者还是资深开发者都能从中受益。
30 7
|
9天前
|
开发者
HTTP状态码是由网页服务器返回的三位数字响应代码,用于表示请求的处理结果和状态
HTTP状态码是由网页服务器返回的三位数字响应代码,用于表示请求的处理结果和状态
16 1
|
20天前
|
缓存 网络协议 安全
揭秘浏览器背后的神秘之旅:一网打尽HTTP请求流程,让你网络冲浪更顺畅!
【8月更文挑战第31天】当在浏览器中输入网址并按下回车键时,一系列复杂的HTTP请求流程随即启动。此流程始于DNS解析,将域名转化为IP地址;接着是与服务器的TCP三次握手建立连接。连接建立后,浏览器发送HTTP请求,其中包含请求方法、资源及版本等信息。服务器接收请求并处理后返回HTTP响应,包括状态码、描述及页面内容。浏览器解析响应,若状态码为200则渲染页面,否则显示错误页。整个流程还包括缓存处理和HTTPS加密等步骤,以提升效率和保障安全。理解该流程有助于更高效地利用网络资源。通过抓包工具如Wireshark,我们能更直观地观察和学习这一过程。
33 4
|
19天前
|
JSON 监控 API
http 请求系列
XMLHttpRequest(XHR)是一种用于在客户端和服务器之间进行异步HTTP请求的API,广泛应用于动态更新网页内容,无需重新加载整个页面。本文提供了多个官方学习资源,包括MDN Web Docs、WhatWG和W3C的规范文档,涵盖属性、方法、事件及示例代码。XHR的主要应用场景包括动态内容更新、异步表单提交、局部数据刷新等,具有广泛的支持和灵活性,但也存在处理异步请求的复杂性等问题。最佳实践包括使用异步请求、处理请求状态变化、设置请求头、处理错误和超时等。这些资源和实践将帮助你更好地理解和使用XHR。
20 1
|
1月前
|
JSON API 数据格式
Python网络编程:HTTP请求(requests模块)
在现代编程中,HTTP请求几乎无处不在。无论是数据抓取、API调用还是与远程服务器进行交互,HTTP请求都是不可或缺的一部分。在Python中,requests模块被广泛认为是发送HTTP请求的最简便和强大的工具之一。本文将详细介绍requests模块的功能,并通过一个综合示例展示其应用。
|
1月前
|
Web App开发 缓存 JSON
在打开网站时,HTTP请求流程是如何处理的
【8月更文挑战第20天】流程包括:构建请求(如`GET /index.html HTTP/1.1`)、检查本地缓存、获取服务器IP及端口、等待TCP连接队列、建立TCP连接、发送HTTP请求。服务器处理后返回数据与响应头,可选择保持连接开启以便后续请求重用,最后断开TCP连接。