Junit模拟http请求

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;
    }*/
}
时间: 2024-09-20 06:12:15

Junit模拟http请求的相关文章

php模拟post请求发送文件

由于项目需要,需要本地服务器接收数据后,再将数据转发到另外一台服务器上,故要用到模拟post请求发送数据,当然数据中也包含文件流. curl是php比较常用的方式之一,一般代码如下: $params1 = test; $params2 = @.$absolute_path;//如果是文件 则参数为@+绝对路径 $post_data = array( 'params1' => $params1, 'params2' => $params2, ); function postData($url,

【技术干货】Python之模拟http请求测试

首先我们用django建一个简单的web应用,然后启动并访问 1.用python模拟get请求 在浏览器中访问该应用http://127.0.0.1:8000,并通过firebug看下网络请求 一个get请求,状态码为200,然后响应了一些html 用python来替代浏览器模拟试试吧 用python模拟的get,获取返回的状态与内容都是与浏览器一致的,只是html没有渲染出界面来   2.用python模拟post 在浏览器中输入页面http://127.0.0.1:8000/index/,然

Java模拟HTTP请求如何获取请求页面中ajax方法的返回值

问题描述 Java模拟HTTP请求如何获取请求页面中ajax方法的返回值 我有一个AAA.JSP页面是通过加载百度的地图API的JS文件,再调用其中的ajax请求方法获取地理坐标.地理坐标在该ajax方法的返回参数中的.我现在需要在服务器端获取地理位置信息,因此我通过java程序模拟HTTP请求,去访问AAA.JSP,但因为ajax是异步的,模拟程序访问该页面的时候,其中的ajax方法还没执行结束,服务器就返回了该页面的静态HTML内容,导致我无法获取地理位置信息.请问如何让服务器端在ajax执

服务器-c 模拟http请求,如何获取页面中的图片?

问题描述 c 模拟http请求,如何获取页面中的图片? 1.我编写了一个SOCKET程序,功能类似代理软件,主要是将指定服务器的页面转发到本地. 2.在浏览器访问本地地址时,就会打开指定服务器的页面 3.现在的问题是可以获取到文本数据,如: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />? <html> <head> </head&g

PHP模拟http请求的方法详解_php技巧

本文实例讲述了PHP模拟http请求的方法.分享给大家供大家参考,具体如下: 方法一:利用php的socket编程来直接给接口发送数据来模拟post的操作. 建立两个文件post.php,getpost.php post.php内容如下: <?php $flag = 0; $params = ''; $errno = ''; $errstr = ''; //要post的数据 $argv = array( 'var1'=>'abc', 'var2'=>'how are you , my f

轻松把玩HttpAsyncClient之模拟post请求示例

       如果看到过我前些天写过的<轻松把玩HttpClient之模拟post请求示例>这篇文章,你再看本文就是小菜一碟了,如果你顺便懂一些NIO,基本上是毫无压力了.因为HttpAsyncClient相对于HttpClient,就多了一个NIO,这也是为什么支持异步的原因.        不过我有一个疑问,虽说NIO是同步非阻塞IO,但是HttpAsyncClient提供了回调的机制,这点儿跟netty很像,所以可以模拟类似于AIO的效果.但是官网上的例子却基本上都是使用Future&l

java http get post 各种请求,模拟浏览器请求

package com.hlzt.wx.util.http; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import com.hlzt.wx.util.token.GlobalAccessTokenUtils; public class Htt

PHP socket 模拟POST 请求实例代码_php技巧

我们用到最多的模拟POST请求几乎都是使用php curl来实现了,没考虑到PHP socket也可以实现,今天看到朋友写了一文章,下面我来给大家分享一下PHP socket模拟POST请求实例. 以前模拟post请求俺都用PHP curl扩展实现来着,没想过PHP socket也可以实现.最近翻了下相关资料才发现原来没有那么高深,只是以前一直没有完全理解post的原理和本质而已,其实就是发送给目的程序一个标志为post的协议串如下: POST /目的程序url HTTP/1.1 Accept:

php curl模拟post请求和提交多维数组的示例代码_php实例

下面一段代码给大家介绍php curl模拟post请求的示例代码,具体代码如下: <?php $uri = "http://www.cnblogs.com/test.php";//这里换成自己的服务器的地址 // 参数数组 $data = array ( 'name' => 'tanteng' // 'password' => 'password' ); $ch = curl_init (); // print_r($ch); curl_setopt ( $ch, C