java模拟简易Http的get和post请求

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java模拟简易Http的get和post请求相关的知识,希望对你有一定的参考价值。

背景

  笔者做java web后台开发,经常需要和前端同学交互,由于前后台工作效率不一,总会有时间差,以前总时傻傻等待或是轮询:“喂,前端写好了没,交互一下”。之前也有师弟告诉我,火狐浏览器有自带模拟Http请求的插件,但是,作为一名程序猿,还是想通过代码自己写个工具类。于是乎,就有了HttpHelper。

设计

  get和post协议是web开发最常用的两种方式,两者传输数据的不用在于:get请求将数据拼接在url地址里,而post请求则将数据放在请求体里。于是在工具类里定义两个方法相应的去处理两种请求,再将两个方法相同的地方(请求头设定,数据解析)抽取出来,代码复用。笔者做的web项目前后台交互数据均用json格式,因此数据存储在Map中。

代码

package util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Simulating Http Request
 * Created by Michael Wong on 2016/2/24.
 */
public class HttpHelper {

    private static final String GET_METHOD = "GET";

    private static final String POST_METHOD = "POST";

    private HttpHelper() {

    }

    /**
     * Get request
     * @param url 
     * @param parameters 
     * @return responseBody
     */
    public static String get(String url, Map<String, Object> parameters) {

        url = url + "?" + parseParameters(parameters);

        HttpURLConnection connection = null;

        try {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestMethod(GET_METHOD);

            setRequestProperty(connection);

            connection.connect();

            return receiveResponse(connection);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return null;
    }

    /**
     * Post request
     * @param url 
     * @param parameters 
     * @return responseBody
     */
    public static String post(String url, Map<String, Object> parameters) {

        HttpURLConnection connection = null;
        BufferedWriter writer = null;

        try {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestMethod(POST_METHOD);

            setRequestProperty(connection);

            writer = new BufferedWriter(
                    new OutputStreamWriter(connection.getOutputStream()));
            writer.write(parseParameters(parameters));
            writer.flush();

            return receiveResponse(connection);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (connection != null) {
                connection.disconnect();
            }
        }

        return null;
    }

    /**
     * Set Request Properties
     * @param connection HttpConnection
     */
    private static void setRequestProperty(HttpURLConnection connection) {
        connection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 " +
                "(Windows NT 6.1; WOW64) AppleWebKit/537.36 " +
                "(Khtml, like Gecko) Chrome/47.0.2526.111 Safari/537.36");
        if (POST_METHOD.equals(connection.getRequestMethod())) {
            connection.setDoOutput(true);
        }
        connection.setDoInput(true);
    }

    /**
     * Parse parameters
     * @param parameters 
     * @return parsed parameters
     */
    private static String parseParameters(Map<String, Object> parameters) {
        if (parameters == null) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        Set<Map.Entry<String, Object>> set = parameters.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = set.iterator();

        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            result.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }

        return result.substring(0, result.lastIndexOf("&"));
    }

    /**
     * Read input stream
     * @param connection Http Connection
     * @return response body
     * @throws IOException
     */
    private static String receiveResponse(HttpURLConnection connection) throws IOException {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuilder receivedContent = new StringBuilder(1024);
        String line = "";
        while((line = reader.readLine()) != null) {
            receivedContent.append(line);
        }
        reader.close();
        return receivedContent.toString();
    }

}

测试

public class HttpSimulation {

    @Test
    public void testSignInFromCubeMaster() {
        int userId = 5;

        String url = "http://localhost:8080/cube/user/signInFromCubeMaster";

        Map<String, Object> params = MapFactory.newHashMap();
        params.put("userId", userId);

        HttpHelper.get(url, params);

    }
}

结束语

  Beta版,简单请求使用没问题,难免有Bug,欢迎各路高手批评指正,代码已上传至Github,欢迎打星星。

以上是关于java模拟简易Http的get和post请求的主要内容,如果未能解决你的问题,请参考以下文章

使用PHP Socket 编程模拟Http post和get请求

iOS 在线模拟post请求和get请求

JAVA模拟HTTP post请求上传文件

Java 模拟 HTTP Get Post 请求实现论坛自动回帖

接口自动化测试-Mock Get和Post请求

Java socket模拟HTTP协议客户端之POST请求