HttpClientUtil工具类封装

本文介绍了一个基于Apache HttpClient的Java工具类实现,包括GET和POST请求的封装,展示了如何设置请求参数、请求头以及处理响应结果。适用于网络请求场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.jd.ng.shiro.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**

  • @Author: husToy.Wang
  • @Date: 2019/8/5 9:38
  • @Version 1.0
    */
    public class HttpClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
    • 封装 doGet方法,执行
    • @param url
    • @return
      */
      public static String doGet(String url) {

      CloseableHttpClient httpClient = HttpClients.createDefault();

      HttpGet httpGet = new HttpGet(url);

      /**
      • 设置请求头
        */
        //httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

      CloseableHttpResponse response = null;

      try {
      response = httpClient.execute(httpGet);

       if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
           HttpEntity entity = response.getEntity();
      
           String result = EntityUtils.toString(entity, "UTF-8");
      
           EntityUtils.consume(entity);
      
           httpClient.close();
      
           return result;
       }
       httpClient.close();

      } catch (IOException e) {
      logger.error("httpClient.doGet.error:{}", e.getMessage());
      return null;
      }

      return null;
      }

    /**
    • 封装 post请求
    • @return
      */
      public static String doPost(String url) throws IOException {
      String result = null;

      CloseableHttpClient httpClient = HttpClients.createDefault();

      CloseableHttpResponse response = null;

      try {

       HttpPost httpPost = new HttpPost(url);
      
       // 定义请求的配置
       RequestConfig config = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(2000).build();
       httpPost.setConfig(config);
      
      
       List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
       parameters.add(new BasicNameValuePair("scope", "project"));
       parameters.add(new BasicNameValuePair("q", "java"));
      
       // 提交参数发送请求
       UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameters);
      
       // 请求中设置请求体
       httpPost.setEntity(urlEncodedFormEntity);
      
      
       // 如果需要,设置请求头,多个请求头
       //Header[] headers = {new BasicHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8")};
       //httpPost.setHeaders(headers);
      
      
       response = httpClient.execute(httpPost);
      
       HttpEntity entity = response.getEntity();
      
       if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      
           result = EntityUtils.toString(entity, "UTF-8");
      
           EntityUtils.consume(entity);
           httpClient.close();
           return result;
       }

      } catch (Exception e) {
      logger.error("httpClient.doPost.error:{}", e.getMessage());
      return null;
      }

      return null;
      }

}

转载于:https://www.cnblogs.com/leigepython/p/11301448.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值