java编写http请求发送get与put请求以及http请求工具包

1,原生get请求

  @Test
    public void testGet() throws Exception {
        //get请求直接在url后面拼接
        URL uri = new URL("http://130.0.0.123:8959/hdcy/fzbt/dchzxq?hzid=74f1dbeffaca4aa6adefdb1d377149ab");
        HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(15000);
        String result = "";
        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
           BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            // 存放数据
            StringBuilder sb = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                sb.append(temp);
                sb.append(System.lineSeparator());  // 这里需要追加换行符,默认读取的流没有换行符,需要加上才能符合预期
            }
            result = sb.toString();
        }
        System.out.println(result);
    }

2,原生post请求

    @Test
    public void testPost() throws Exception {
        //一定要加 http或者 https
        URL uri = new URL("http://130.0.0.123:8959/hdcy/fzbt/hzxq");
        HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
        connection.setRequestMethod("POST");

        connection.setConnectTimeout(15000);
        // 设置读取主机服务器返回数据超时时间:60000毫秒
        connection.setReadTimeout(60000);
        /**post请求需要添加的参数开始**/
        // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("content-type","application/json;charset=UTF-8");
        //默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
        connection.setDoOutput(true);
        // 通过连接对象获取一个输出流
        OutputStream os = connection.getOutputStream();
        //POST请求需要传递的参数,以bytes数组格式传递
        os.write("{\"hzid\":\"74f1dbeffaca4aa6adefdb1d377149ab\"}".getBytes());
        /**post请求需要添加的参数结束**/

        String result = "";
        if (connection.getResponseCode() == 200) {
            InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            // 存放数据
            StringBuilder sb = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                sb.append(temp);
                sb.append(System.lineSeparator());  // 这里需要追加换行符,默认读取的流没有换行符,需要加上才能符合预期
            }
            result = sb.toString();
        }
        System.out.println(result);
    }

3,apache封装get请求

 @Test
    public void testApacheGet() throws  Exception {
        String content = null;
        // 创建 HttpClient 对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建 Http GET 请求
        HttpGet httpGet = new HttpGet("http://130.0.0.123:8959/hdcy/nw/fzbt/dchzxq?hzid=74f1dbeffaca4aa6adefdb1d377149ab");
        CloseableHttpResponse response = null;
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                System.out.println("response.getEntity(): "+response.getEntity());
                //响应体内容
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        System.out.println(content);
    }

4,apache封装post请求

  @Test
    public void testApachePut() throws  Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = null;
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost("http://130.0.0.123:8959/hdcy/nw/fzbt/hzxq");
        //设置请求的json对象,如果是form表单提交则是new UrlEncodedFormEntity(**);
        httpPost.setEntity(new StringEntity("{\"hzid\":\"74f1dbeffaca4aa6adefdb1d377149ab\"}", ContentType.APPLICATION_JSON));
        // httpClient对象执行post请求,并返回响应参数对象
        httpResponse = httpClient.execute(httpPost);
        // 从响应对象中获取响应内容
        HttpEntity entity = httpResponse.getEntity();
        result = EntityUtils.toString(entity);
        System.out.println(result);
    }

5,http请求工具类

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: yll
 * @description:
 * @date: 2022\8\26 0026.
 */
@Slf4j
public class HttpClientHelper {
    /**
     * HttpClient
     */
    private static CloseableHttpClient client = null;

    /**
     * 请求超时时间
     */
    private static final int CONNECTION_REQUEST_TIMEOUT = 60 * 1000;

    /**
     * 连接超时时间
     */
    private static final int CONNECT_TIMEOUT = 300 * 1000;

    /**
     * 读取超时时间
     */
    private static final int SOCKET_TIMEOUT = 60 * 1000;

    /**
     * 线程池最大连接数
     */
    private static final int MAX_TOTAL = 1000;

    /**
     * 单个路由最大连接数
     */
    private static final int MAX_PER_ROUTE = 100;

    /**
     * 初始化 HTTPClient
     *
     * @return CloseableHttpClient
     */
    private static synchronized CloseableHttpClient getHttpClient() {
        if (client == null) {
            ConnectionSocketFactory connectionSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
            LayeredConnectionSocketFactory layeredConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", connectionSocketFactory).register("https", layeredConnectionSocketFactory).build();
            //HttpClient 连接池
            PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
            poolingHttpClientConnectionManager.setMaxTotal(MAX_TOTAL);
            poolingHttpClientConnectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
            //Request配置
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).build();
            client = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).setDefaultRequestConfig(requestConfig).build();
        }
        return client;
    }

    /**
     * Response回调函数
     */
    private static ResponseHandler<String> responseHandler = response -> {
        //状态码200时返回响应值
        int status = response.getStatusLine().getStatusCode();
        log.debug("请求返回状态码: " + status);
        if (status == 200) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity) : null;
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    };


    /**
     * Get请求
     *
     * @param url 请求路径+参数
     * @return String
     */
    public static String doGet(String url) throws IOException {
        client = getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        return client.execute(httpGet, responseHandler);
    }

    /**
     * Get请求
     *
     * @param url    请求路径
     * @param params 参数Map集合
     * @return String
     */
    public static String doGet(String url, Map<String, String> params) throws URISyntaxException, IOException {
        client = getHttpClient();
        URIBuilder uriBuilder = new URIBuilder(url);
        if (null != params) {
            for (String key : params.keySet()) {
                uriBuilder.addParameter(key, params.get(key));
            }
        }
        URI uri = uriBuilder.build();
        HttpGet httpGet = new HttpGet(uri);
        return client.execute(httpGet, responseHandler);
    }

    /**
     * Form表单提交
     *
     * @param url    请求地址
     * @param params 参数
     * @return String
     */
    public static String doPost(String url, Map<String, String> params) throws IOException {
        client = getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        if (null != params) {
            List<NameValuePair> paramList = new ArrayList<>();
            for (String key : params.keySet()) {
                paramList.add(new BasicNameValuePair(key, params.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(paramList, "utf-8"));
        }
        return client.execute(httpPost, responseHandler);
    }

    /**
     * 发送Json数据
     *
     * @param url
     * @param jsonStr
     * @return
     */
    public static String doPostJson(String url, String jsonStr) throws IOException {
        client = getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(jsonStr, ContentType.APPLICATION_JSON));
        return client.execute(httpPost, responseHandler);
    }

    /**
     * 发送PUT Json数据
     * @param url
     * @param jsonStr
     * @return
     * @throws IOException
     */
    public static String doPutJson(String url, String jsonStr) throws IOException{
        System.out.println(jsonStr);
        client = getHttpClient();
        HttpPut httpPut = new HttpPut(url);
        httpPut.setEntity(new StringEntity(jsonStr, ContentType.APPLICATION_JSON));
        return client.execute(httpPut, responseHandler);
    }

    /**
     * 发送Soap数据
     *
     * @param url     请求地址
     * @param soapStr soap封装格式字符串
     * @return Soap XML格式
     */
    public static String doPostSoap(String url, String soapStr) throws IOException {
        client = getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
        httpPost.setEntity(new StringEntity(soapStr, ContentType.APPLICATION_SOAP_XML));
        return client.execute(httpPost, responseHandler);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值