栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java基础系列:httpclient请求GET和POST接口

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java基础系列:httpclient请求GET和POST接口

1 简介 1.1 Java请求GET和POST接口

Java请求Http接口常用的方式有三种,如下表

序号工具描述应用案例
1URLConnectionJava原生,java.net.URLConnectionhttps://blog.csdn.net/Xin_101/article/details/122440247
2HttpURLConnectionJava原生,java.net.HttpURLConnectionhttps://blog.csdn.net/Xin_101/article/details/122449254
3httpclient第三方工具,org.apache.httpcomponentshttps://blog.csdn.net/Xin_101/article/details/122449693

本章讲解httpclient请求接口。

1.2 httpclient

原Apache httpclient通用依赖为:commons-httpclient,现已将该功能迁移到:org.apache.httpcomponents


    commons-httpclient
    commons-httpclient
    3.1

Maven仓库告知如下:


    org.apache.httpcomponents
    httpclient
    4.5.13

2 接口

表单接口:

2 测试 2.1 Code
package com.monkey.java_study.web;

import com.google.gson.Gson;
import com.monkey.java_study.common.entity.PageEntity;
import org.apache.http.HttpEntity;
import org.apache.http.NamevaluePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNamevaluePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;


public class HttpClientTest {

    private static final Logger logger = LogManager.getLogger(HttpClientTest.class);

    
    public static String doGet(String url) {
        try {
            // 创建客户端
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // 建立连接
            HttpGet httpGet = new HttpGet(url);
            // 请求配置:超时时间,单位:毫秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpGet.setConfig(requestConfig);
            // 设置请求头:内容类型
            httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");

            return getResponse(httpClientBuilder, httpGet);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    
    public static String doPostFormData(String url, Map paramMap) {
        try {
            // 创建客户端
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // 建立连接
            HttpPost httpPost = new HttpPost(url);
            // 请求配置:超时时间,单位:毫秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            // 设置请求头:内容类型
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            if (Objects.nonNull(paramMap) && !paramMap.isEmpty()) {
                List formDataList = new ArrayList<>();
                Set> entrySet = paramMap.entrySet();
                for (Map.Entry mapEntry : entrySet) {
                    formDataList.add(new BasicNamevaluePair(mapEntry.getKey(), mapEntry.getValue().toString()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(formDataList, "UTF-8"));
            }

            return postResponse(httpClientBuilder, httpPost);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    
    public static String doPostJson(String url, String params) {
        try {
            // 创建客户端
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // 建立连接
            HttpPost httpPost = new HttpPost(url);
            // 请求配置:超时时间,单位:毫秒
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            // 设置请求头:内容类型
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(params);
            stringEntity.setContentType("text/json");
            httpPost.setEntity(stringEntity);
            return postResponse(httpClientBuilder, httpPost);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    
    public static String getResponse(HttpClientBuilder httpClientBuilder, HttpGet httpGet) {
        try (CloseableHttpResponse closeableHttpResponse = httpClientBuilder.build().execute(httpGet)) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            return EntityUtils.toString(httpEntity, "UTF-8");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    
    public static String postResponse(HttpClientBuilder httpClientBuilder, HttpPost httpPost) {
        try (CloseableHttpResponse closeableHttpResponse = httpClientBuilder.build().execute(httpPost)) {
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            return EntityUtils.toString(httpEntity, "UTF-8");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static void main(String[] args) {

        // GET:请求
        String getUrl = "http://localhost:9121/api/v1/mongodb/read?userId=0x001";
        String getResponse = doGet(getUrl);
        logger.info(">>>>>>>>>Get response:{}", getResponse);

        // POST:请求携带form-data参数
        String postFormDataUrl = "http://localhost:9121/api/v1/parameter/annotation/form-data";
        Map mapFormData = new HashMap<>();
        mapFormData.put("name", "xiaohong");
        String formDataResponse = doPostFormData(postFormDataUrl, mapFormData);
        logger.info(">>>>>>>>>Post form data response:{}", formDataResponse);

        // POST:请求携带JSON参数
        String postUrl = "http://localhost:9121/api/v1/mongodb/page";
        // 入参实体
        PageEntity pageEntity = new PageEntity(1, 2);
        Gson gson = new Gson();
        // 实体转JSON字符串
        String jsonString = gson.toJson(pageEntity);
        String postResponse = doPostJson(postUrl, jsonString);
        logger.info(">>>>>>>>>>Post json response:{}", postResponse);
    }
}

2.2 测试

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/703556.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号