美文网首页
java发送http请求

java发送http请求

作者: IT小池 | 来源:发表于2020-02-16 22:52 被阅读0次

    1.spring中的RestTemplate发送请求

        @Test
        public void testRestplateGet() throws IOException {
            // String url = "http://localhost:8080/test2?id=111111";
            String url = "http://localhost:8080/test2?id={id}";
    
            RestTemplate restTemplate = new RestTemplate();
            // get 无参数请求
            //Map result = restTemplate.getForObject(url,Map.class);
            Map<String,Object> params = new HashMap<>();
            params.put("id",66666);
    
            Map result = restTemplate.getForObject(url,Map.class,params);
            System.out.println(result);
        }
    
        @Test
        public void testRestplatePost() throws IOException {
            String url = "http://localhost:8080/test1";
    
            Map params = new HashMap();
            params.put("id","xiaochi");
    
            RestTemplate restTemplate = new RestTemplate();
            // post 无参数请求
            //Map map = restTemplate.postForObject(url, new HashMap(), Map.class);
            Map map = restTemplate.postForObject(url, params, Map.class);
            System.out.println(map);
        }
    

    2.HttpComponents-Client的发送请求

    导包:

    <dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpclient</artifactId>
          <version>4.5.10</version>
    </dependency>
    <!-- StringEntity设置传输参数时,使用fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.62</version>
    </dependency>
    

    创建工具类HttpUtils

    package com.springboot.demo;
    
    import com.alibaba.fastjson.JSON;
    import org.apache.http.HttpEntity;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.HttpClientUtils;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    /**
     * httpClient工具类
     */
    public class HttpUtils {
    
        /**
         * 发送 get 请求(无参数)
         * @param url
         * @return
         * @throws IOException
         */
        public static Map<String,Object> doGet(String url) throws IOException {
            return doGet(url,new HashMap<>());
        }
    
        /**
         * 发送 get 请求(有参数)
         * @param url
         * @param params
         * @return
         * @throws IOException
         */
        public static Map<String,Object> doGet(String url, Map<String,Object> params) throws IOException {
            if (params.size() > 0){
                url = url + "?" + handleParams(params);
            }
            //start get
            //1、创建客户端
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 超时设置(可不设置)
            RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(5000) //连接超时
                    .setConnectionRequestTimeout(5000)//请求超时
                    .setSocketTimeout(5000)
                    .setRedirectsEnabled(true)  //允许自动重定向
                    .build();
            //2、创建Http的请求方式get,post etc... 需要传入请求地址
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);// 设置配置
            //3、httpClient执行请求,并获取返回结果
            CloseableHttpResponse response = httpClient.execute(httpGet);
            //4、输出获取到的结果
            //从response中取出返回的entity
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            //输出
            //System.out.println("get返回状态行:"+response.getStatusLine());
            //System.out.println("get返回结果:"+ result);
    
            //5、关闭连接 也可以直接调用close()方法
            HttpClientUtils.closeQuietly(response);
    
            Map<String,Object> map = new HashMap<>();
            map.put("result",JSON.parseObject(result, Map.class));
            map.put("status",response.getStatusLine().getStatusCode());
            return map;
        }
    
        /**
         * 拼接 get参数
         * @param params
         * @return
         */
        private static String handleParams(Map<String,Object> params){
            // 处理参数
            StringBuffer buffer = new StringBuffer();
            if (params.size() > 0){
                Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, Object> entry  = iterator.next();
                    buffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            return buffer.toString().substring(0,buffer.length()-1);
        }
    
        /**
         * 发送 post 请求(无参数)
         * @param url
         * @return
         * @throws IOException
         */
        public static Map<String, Object> doPost(String url) throws IOException {
            return doPost(url,new HashMap<>());
        }
    
        /**
         * 发送 post 请求(有参数)
         * @param url
         * @param params
         * @return
         * @throws IOException
         */
        public static Map<String, Object> doPost(String url, Map<String,Object> params) throws IOException {
            //start post
            //1、创建客户端
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 超时设置(可不设置)
            RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(5000) //连接超时
                    .setConnectionRequestTimeout(5000)//请求超时
                    .setSocketTimeout(5000)
                    .setRedirectsEnabled(true)  //允许自动重定向
                    .build();
            //1、创建post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig); // 设置配置
            httpPost.addHeader("Content-Type","text/html; chartset=UTF-8"); // 表单提交,默认方式是 json 格式
            //2、设置请求参数HttpEntity
            //StringEntity的方式,这种方式比较自由,可以传输自定义的数据格式,只需要后台能处理即可
            //这种方式是真正的post请求,请求参数是防止body中,后台通过流的方式获取数据
            //JSONObject使用阿里巴巴的fastjson
            //创建StringEntity,并设置ContentType
            StringEntity stringEntity = new StringEntity(JSON.toJSONString(params), ContentType.APPLICATION_JSON);
            //stringEntity加入http中
            httpPost.setEntity(stringEntity);
            //3、发送http请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            //4、获取返回结果
            String result = EntityUtils.toString(response.getEntity());
            //5、输出结果
            //System.out.println("StringEntity返回状态行:"+response.getStatusLine());
            //System.out.println("StringEntity返回结果:"+result);
            //6、关闭
            HttpClientUtils.closeQuietly(response);
            //end post
    
            Map<String,Object> map = new HashMap<>();
            map.put("result",JSON.parseObject(result, Map.class));
            map.put("status",response.getStatusLine().getStatusCode());
            return map;
        }
    }
    

    创建测试类HttpUtilsTest

    package com.springboot.demo;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class HttpUtilsTest {
    
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        @Test
        public void testHttpGet() throws IOException {
            String url = "http://localhost:8080/test2";
            // 发送 get 请求(无参数)
            // Map<String, Object> result = HttpUtils.doGet(url);
            Map params = new HashMap();
            params.put("id",111111);
            // 发送 get 请求(有参数)
            Map<String, Object> result = HttpUtils.doGet(url,params);
            //System.out.println(result);
            //System.out.println(result.get("status"));
            if (result.get("status").equals(200)){
                System.out.println(result.get("result"));
                Map result1 = (Map) result.get("result");
                System.out.println(result1.get("name"));
            }else{
                System.out.println("请求失败!状态码:" + result.get("status"));
            }
        }
    
        @Test
        public void testHttpPost() throws IOException {
            String url = "http://localhost:8080/test1";
            // 发送 post 请求(无参数)
            // Map<String, Object> result = HttpUtils.doPost(url);
            Map params = new HashMap();
            params.put("id",222222);
            // 发送 post 请求(有参数)
            Map<String, Object> result = HttpUtils.doPost(url,params);
            //System.out.println("结果"+result);
            //System.out.println(result.get("status"));
            if (result.get("status").equals(200)){
                System.out.println(result.get("result"));
                Map result1 = (Map) result.get("result");
                System.out.println(result1.get("name"));
            }else{
                System.out.println("请求失败!状态码:" + result.get("status"));
            }
        }
    }
    

    ok,到此完成

    相关文章

      网友评论

          本文标题:java发送http请求

          本文链接:https://www.haomeiwen.com/subject/jnhvfhtx.html