模拟http请求以及RestTemplate工具类的简单封装

方式一、自己写工具类,使用 Java 自带的 HttpUrlConnection

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Http请求工具类
 *
 * @author : xukun
 * @date : 2020/9/1
 */
public class HttpUtils {

    private static Logger log = LoggerFactory.getLogger(HttpUtils.class);

    public static String sendPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();

        try {
            URL realURL = new URL(url);
            //打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realURL.openConnection();

            //发送post请求必须设置下面两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置请求方式
            conn.setRequestMethod("POST");

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json");

            //连接
            conn.connect();

            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数
            out.write(param);
            out.flush();
            //定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            while ((line = in.readLine()) != null) {
                result.append(line);
            }

        } catch (Exception e) {
            log.info("发送POST请求异常!" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return result.toString();
    }

    public static void main(String[] args) {
        String url = "http://xxx.xx.xx.xx:xx/api/user/getUserByCardId";//自己需要的
        String params = "{\"appCode\":10010,\"cardId\":\"420683199804121315\", \"userId\":\"339f27c1-43d0-40aa-b473-17c1ff823d7f\"}";//自己需要的
        String result = HttpUtils.sendPost(url, params);
        System.out.println("请求结果:"+result);
}
}

方式二、使用RestTemplate

说明:方式一,显而易见,代码很复杂,要设置一系列东西,还要担心资源回收,使用RestTemplate可以用优雅的方式来发HTTP请求。

RestTemplate简介

RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现。
在这里以POST和GET请求为例,将其封装到一个工具类中:

RestTemplateUtils.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author : xukun
 * @date : 2020/9/1
 */
public class RestTemplateUtils {

    static RestTemplate restTemplate;

    static {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        restTemplate = new RestTemplate(factory);
    }

    /**
     * POST请求方式,参数为JSON格式
     *
     * @param url   请求的URL
     * @param param 参数 (可为空)
     * @return
     */
    public static JSONObject doPostByJson(String url, JSONObject param) {

        JSONObject json = new JSONObject();

        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        //设置为JSON格式
        headers.setContentType(MediaType.APPLICATION_JSON);
        //创建请求
        HttpEntity<JSONObject> request = new HttpEntity<>(param, headers);

        ResponseEntity<String> response = null;
        String responseBody = "";
        try {
            //第一个参数,请求的url;第二个参数,http请求;第三个参数,响应的类型
            response = restTemplate.postForEntity(url, request, String.class);
            //调整响应体的编码格式
            responseBody = new String(response.getBody().getBytes("utf-8"), "utf-8");

        } catch (RestClientException clientExp) {//请求出错
            json.put("message", clientExp.getMessage());
            return json;
        } catch (UnsupportedEncodingException encodingExp) {//转码出错
            json.put("message", "结果集转码错误");
            json.put("result", false);
            return json;
        }

        //返回相应的JSON数据
        json = JSON.parseObject(responseBody);
        return json;
    }

    /**
     * Get请求方式,参数为JSON格式,内部会转为指定格式
     *
     * @param url   请求的URL
     * @param param 参数 (可为空)
     * @return
     */
    public static JSONObject doGetByJson(String url, JSONObject param) {

        if (parseURLParam(param) != null && parseURLParam(param) != "") {
            url = url + "?" + parseURLParam(param);
        }

        JSONObject json = new JSONObject();

        ResponseEntity<String> response = null;
        String responseBody = "";
        try {
            //第一个参数,请求的url;第二个参数,响应的类型
            response = restTemplate.getForEntity(url, String.class);
            //调整响应体的编码格式
            responseBody = new String(response.getBody().getBytes("utf-8"), "utf-8");

        } catch (RestClientException clientExp) {//请求出错
            json.put("message", clientExp.getMessage());
            return json;
        } catch (UnsupportedEncodingException encodingExp) {//转码出错
            json.put("message", "结果集转码错误");
            json.put("result", false);
            return json;
        }

        //返回相应的JSON数据
        json = JSON.parseObject(responseBody);
        return json;
    }

    /**
     * 将JSON参数转换为k1=v1&k2=v2格式
     *
     * @param params
     * @return String
     */
    private static String parseURLParam(JSONObject params) {
        StringBuilder p = new StringBuilder();
        int current = 0;
        for (Map.Entry<String, Object> param : params.entrySet()) {
            current++;
            p.append(param.getKey() + "=" + param.getValue());
            if (current < params.entrySet().size()) {
                p.append("&");
            }
        }
        return p.toString();
    }

    public static void main(String[] args) {
        String postUrl = "http://xxx.xx.xx.xx:xx/api/user/getUserByCardId";//自己定义
        System.out.println("=====POST=====");
        String postParam = "{\"appCode\":10010,\"cardId\":\"420683199804121315\", \"userId\":\"339f27c1-43d0-40aa-b473-17c1ff823d7f\"}";//自己定义
        JSONObject param = JSONObject.parseObject(postParam);
        JSONObject result = doPostByJson(postUrl, param);
        System.out.println("Post响应结果:" + result);
    }
}

以上就是RestTemplate的简单使用。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值