封装http请求

本文介绍了一种在Java中封装HTTP请求的方法,包括GET和POST请求的实现,以及如何使用Apache HttpClient库进行请求的发送。此外,还展示了如何处理响应,并提供了一个实际的例子,说明了如何使用这些封装的方法。

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

在开发当中调其他系统请求或模拟前端调请求有时会使用到http请求,但java原生类还是比较难用的,一般会自己封装一下,本文展示http请求的一般封装,可以直接拷贝使用。

package com.zqsign.app.privatearbitrate.util;

import org.apache.http.Header;
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.client.utils.URIBuilder;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {


        // 创建Httpclient对象
        CloseableHttpClient httpclient = createCustomClient();

        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = createCustomClient();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url, String body) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = createCustomClient();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (body != null) {
                httpPost.setEntity(new StringEntity(body, "utf-8"));
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, (String) null);
    }

    public static String doPostJson(String url, String json, Header... headers) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = createCustomClient();
        CloseableHttpResponse response = null;
        String resultString = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            //添加请求头
            if (headers != null && headers.length > 0) {
                for (Header header : headers) {
                    if (header != null) {
                        httpPost.addHeader(header);
                    }
                }
            }
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200) {
            	resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }else {
            	resultString = "调用服务端异常,请联系相关人员";
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static CloseableHttpClient createCustomClient() {
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(120 * 1000)
                .setConnectTimeout(120 * 1000)
                .setConnectionRequestTimeout(120 * 1000)
                .setStaleConnectionCheckEnabled(true)
                .build();

        return HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    }
}

使用:

  @Test
    public void evidenceTest() {

        long a = System.currentTimeMillis();
        Map<String,Object> param = getParam("evidence");
        long b = System.currentTimeMillis();
        System.out.println("拼接数据时间:" + (b-a));
        String str = JSON.toJSONString(param);
        String sign = RsaSign.sign(str, TENANT_PRIVATE_KEY);
        BasicHeader header = new BasicHeader("sign_val", sign);
        System.out.println(str);

        long start = System.currentTimeMillis();
        String res = HttpClientUtil.doPostJson("http://localhost:8080/web/trade-upload", JSON.toJSONString(param),header);
        long end = System.currentTimeMillis();

        System.out.println("请求接口时间:" + (end-start));
        System.out.println("接口反馈信息:" + res);

    }

当然,现在已经不用自己封装了,spring3.0之后提供了org.springframework.web.client.RestTemplate类来供我们发送http请求。

### 回答1: Qt是一个功能强大的跨平台开发框架,其中包括了丰富的网络模块,可以轻松地实现HTTP请求。对于HTTP请求封装,主要包括以下几个方面。 1. QNetworkAccessManager类 QNetworkAccessManager类是Qt网络模块的核心类之一,它负责管理所有的网络请求。具体而言,它能够发出发出http请求,接收响应数据,并负责处理中间操作例如网络重定向、HTTP认证、代理等。总的来说,使用该类可以轻松完成HTTP请求封装。 2. QNetworkRequest类 QNetworkRequest类封装了一个HTTP请求,包括URL、HTTP请求头、HTTP请求方法等。我们可以通过设置这些属性来制定HTTP请求。例如,构造一个GET请求,设置请求头: QNetworkRequest request(QUrl("http://www.baidu.com"));request.setHeader(QNetworkRequest::ContentTypeHead er, "application/x-www-form-urlencoded"); 3. QNetworkReply类 QNetworkReply类封装了一个HTTP响应,它可以提取包括HTTP响应码和响应头在内的所有与HTTP请求及响应相关的信息。可以通过这个类获取HTTP返回的结果。 总结:Qt提供了完善的网络模块,支持httphttps协议,可以轻松实现http请求封装,自定义请求头,处理响应信息等。本质上就是通过一个网络管理器,发出请求,获取响应,进而完成http请求封装。因此,使用Qt实现http请求是一种简洁有效的方案。 ### 回答2: Qt是一款跨平台的C++开发框架,它提供了用于网络通信的相关组件,其中也包括了HTTP请求封装类。在Qt中,可以使用QNetworkAccessManager类来封装HTTP请求,这个类简化了HTTP请求的发送和接收,并提供了一些有用的事件和回调函数。 使用QNetworkAccessManager类发送HTTP请求时,需要先创建一个QNetworkRequest对象,指定要发送的URL地址和请求方法。可以在请求中添加自定义的HTTP请求头和请求体。接着,使用QNetworkAccessManager的post()、get()、put()等方法发送请求。当响应结果返回时,可以在接收的数据中解析出HTTP响应头和响应体,QNetworkAccessManager也提供了相关的信号和槽函数。 QNetworkAccessManager使用异步请求方式,即发送请求后会立即返回,等待从远端接收响应结果。如果需要同步请求,可以使用QNetworkReply类的waitForFinished()方法,但不建议在主线程中使用。 在Qt中,也提供了第三方的HTTP库,例如QHttpEngine和Qhttplib,可以更简便地实现HTTP请求。但使用Qt自带的QNetworkAccessManager类是更加轻量和简单的方式,可以避免额外依赖,并且具有更好的可移植性和跨平台性。 ### 回答3: Qt是一种跨平台的C++应用程序框架,提供了许多丰富的库,其中包括Qt网络库(QtNetwork),可轻松地进行HTTP请求。Qt封装了许多网络协议,例如TCP、UDP、HTTP、FTP等,使得开发者可以轻松地进行网络操作。 Qt提供了QNetworkAccessManager类,用于处理网络请求。它支持GET、POST、PUT、DELETE等HTTP请求方式。可以通过QNetworkRequest类设置请求头和请求参数。QNetworkAccessManager在请求完成后会发出信号,开发者可以捕获信号并进行逻辑处理。 除了QNetworkAccessManager,Qt还提供了QHttp类,用于发送和接收HTTP请求和响应。QHttp类是基于底层网络套接字的,需要开发者自行处理协议和数据传输。但是,在Qt5中,已不推荐使用QHttp类,而是推荐使用QNetworkAccessManager。 总之,Qt提供了一种简便的方式,使得开发者可以轻松地进行HTTP请求。无论是使用QNetworkAccessManager还是QHttp类,都可以轻松地进行网络请求并处理响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值