java 实现 Http 请求,使用 HttpClient 库

发布时间 2023-12-04 17:23:54作者: 海乐学习

HttpClient 是一个 HTTP 客户端库,提供了向 HTTP 服务器发送请求和处理响应的方法。

它支持多种请求协议,如 GET、POST 等,并允许开发者自由地设置请求头、请求参数、连接池等。HttpClient 还提供了基于线程池的异步请求处理方式。

pom.xml

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
</dependency>

引用

//http
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.HttpEntity;
//slf4j
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//json
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

Get 方式

    //http请求GET
    public static String httpGet(String url){
        //发送请求的URL
        //String url = "http://localhost:5011/httpCli?action=dial&caller=3012&callee=13941128299";
        logger.debug("httpPost() 准备HttpPost请求! " + url + " " + "");
        String result ="-1";
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            //HttpGet httpget = new HttpGet("https://www.example.com");
            HttpGet httpget = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpget);

            try {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
                EntityUtils.consume(entity);

                System.out.println(result);
            } finally {
                response.close();
            }
        }catch (ClientProtocolException ex){
            logger.error("httpGet() 请求失败 ClientProtocolException " + url + " ",ex.getMessage(),ex);
        }catch (IOException ex){
            logger.error("httpGet() 请求失败 IOException " + url + " ",ex.getMessage(),ex);
        }catch (Exception ex){
            logger.error("httpGet() 请求失败 Exception " + url + " ",ex.getMessage(),ex);
        }

        logger.debug("httpGet() 请求结果: " + result + " " + url);
        return result;
    }

调用方法

String url = "http://localhost:5011/httpCli?action=attendedTransfer&transExt=1002&transTo=6508";
String http_result=httpGet(url);

Post 方式   Json类型

public static JSONObject httpPostSendRequest(String url,JSONObject param){
        //定义接收数据
        JSONObject result = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        //请求参数转JOSN字符串
        StringEntity entity = new StringEntity(param.toJSONString(), "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try {
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }
        } catch (Exception e) {
            //e.printStackTrace();
            //result.put("error", "连接错误!");
            logger.error("httpPostSendRequest() HttpPost " + "=======连接错误=======");
        }
        return result;
    }

调用方法

        //直接Json对象参数
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("event","NewCdr");
        jsonParam.put("didnumber","");
        jsonParam.put("agentringtime","0");
        jsonParam.put("sn","369264842620");
         
        //或  字符串转成 Json对象
        String strParam="{ \"callerid\": \"013941128270\"  }";
        //将字符串转化成JSONObject
        JSONObject jsonParam= JSON.parseObject(eventJson);

        logger.debug("httpPost() HttpPost请求参数: " + jsonParam.toJSONString() + " " + "");
        //发送请求   
        String url="http://localhost:5011/httpCli.php";

        JSONObject jsonResult=httpPostSendRequest(url,jsonParam);

        logger.debug("httpPost() HttpPost请求结果: " + jsonResult.toString() + " " + "");