apache httpcompontens之HttpAsyncClient使用

闲来无事,研究了会HttpAsyncClient,写了一个工具类,替代现有的http工具类

先是maven依赖

 

	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpasyncclient</artifactId>
		<version>4.1.1</version>
	</dependency>
	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpasyncclient-cache</artifactId>
		<version>4.1.1</version>
	</dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.6</version>
    </dependency>


再是工具类代码

 

 

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * http处理类
 * 使用apache的HttpClient
 * @author zhangle
 */
public class HttpUtil {

    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final ObjectMapper mapper = new ObjectMapper();

    public static String get(String url) throws Exception {
        return asyncRequest("get",url,null,null);
    }

    public static String get(String url, Map<String, String> params) throws Exception {
        return asyncRequest("get",url,params,null);
    }

    public static String post(String url) throws Exception {
        return asyncRequest("post",url,null,null);
    }

    public static String post(String url, Map<String, String> params) throws Exception {
        return asyncRequest("post",url,params,null);
    }

    /**
     * post json对象
     * @param url
     * @param jsonObj
     * @return
     * @throws Exception
     */
    public static String postJson(String url, Object jsonObj) throws Exception {

        RequestConfig requestConfig = createRequestConfig();
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();

        try {
            httpclient.start();

            HttpUriRequest request = createPostJsonRequest(url, jsonObj);
            Future<HttpResponse> future = httpclient.execute(request, null);
            HttpResponse response = future.get(3000,TimeUnit.MILLISECONDS);

            return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);

        } finally {
            httpclient.close();
        }
    }

    public static <T> T postJson(String url, Object jsonObj,Class<T> clazz) throws Exception {

        String res=postJson(url,jsonObj);
        return mapper.readValue(res, clazz);
    }

    public static String asyncRequest(String method,String url, Map<String, String> params, Map<String, String> headers) throws Exception {

        RequestConfig requestConfig = createRequestConfig();
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();

        try {
            httpclient.start();

            HttpUriRequest request = createHttpUriRequest(method, url, params, headers);
            Future<HttpResponse> future = httpclient.execute(request, null);
            HttpResponse response = future.get(3000,TimeUnit.MILLISECONDS);

            return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);

        } finally {
            httpclient.close();
        }
    }

    public static String request(String method,String url, Map<String, String> params, Map<String, String> headers) throws Exception {

        RequestConfig requestConfig = createRequestConfig();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

        try {

            HttpUriRequest request = createHttpUriRequest(method, url, params, headers);
            CloseableHttpResponse response = httpclient.execute(request);

            return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);

        } finally {
            httpclient.close();
        }
    }

    /**
     * 上传文件
     * @param url
     * @param paramName
     * @param file
     * @return
     * @throws Exception
     */
    public static String upload(String url, String paramName, File file) throws Exception {

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)
                .setConnectTimeout(6000)
                .setConnectionRequestTimeout(6000)
                .build();

        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

        try {

            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addBinaryBody(paramName,file);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);

            CloseableHttpResponse response = httpclient.execute(httpPost);
            return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
        } finally {
            httpclient.close();
        }
    }

    private static HttpUriRequest createHttpUriRequest(String method, String url, Map<String, String> params, Map<String, String> headers) {

        RequestBuilder builder = RequestBuilder.create(method.toUpperCase()).setUri(url);
        builder.setCharset(Consts.UTF_8);
        //builder.setConfig(requestConfig);

        Optional.ofNullable(headers).ifPresent(map -> {
            map.forEach((key, val) -> {
                builder.addHeader(key, val);
            });
        });

        Optional.ofNullable(params).ifPresent(map -> {
            map.forEach((key, val) -> {
                builder.addParameter(key, val);
            });
        });

        return builder.build();
    }

    private static HttpUriRequest createPostJsonRequest(String url, Object jsonObj) throws JsonProcessingException {

        RequestBuilder builder = RequestBuilder.post(url);
        builder.setCharset(Consts.UTF_8);
        //builder.setConfig(requestConfig);

        String jsonStr=mapper.writeValueAsString(jsonObj);
        StringEntity jsonEntity=new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
        builder.setEntity(jsonEntity);

        return builder.build();
    }

    private static RequestConfig createRequestConfig() {
        return RequestConfig.custom()
                .setSocketTimeout(3000)
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .build();
    }

    public static void main(String[] args) throws Exception {
        String content=HttpUtil.get("http://www.apache.org/");
        System.out.println(content);
    }

}


然后是运行main方法,测试发送http请求。

    public static void main(String[] args) throws Exception {
        String content=HttpUtil.get("http://www.apache.org/");
        System.out.println(content);
    }

 

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Apache NetBeans IDE 12.4是一款非常优秀的开发工具,它可以帮助开发者更加高效地进行软件开发。使用Apache NetBeans IDE 12.4,开发者可以轻松地创建、编辑和调试各种类型的应用程序,包括Java、C++、PHP、HTML、JavaScript等。此外,该工具还提供了丰富的插件和扩展,可以满足不同开发者的需求。总之,如果你是一名开发者,那么Apache NetBeans IDE 12.4绝对是你不可错过的工具之一。 ### 回答2: Apache NetBeans IDE 12.4是一个开发环境,可以用于各种编程语言和技术的开发。以下是关于如何使用Apache NetBeans IDE 12.4的一些基本信息。 首先,安装和配置Apache NetBeans IDE 12.4。您可以从官方网站上下载最新版本的NetBeans IDE,并按照安装向导进行安装。安装完成后,您还需要配置JDK(Java开发工具包),以便NetBeans可以正确地编译和运行Java程序。该安装和配置过程在官方网站上有详细的说明。 一旦安装和配置完成,您可以打开NetBeans IDE并开始使用它。NetBeans IDE具有直观的用户界面,可帮助您有效地组织和管理项目。您可以创建一个新项目或导入现有项目,并选择适当的编程语言和技术。 在NetBeans IDE中,您可以使用各种功能和工具来开发和调试应用程序。例如,您可以使用代码编辑器编写代码,并获得自动完成和代码提示的建议。还可以使用内置的代码分析工具来检查代码质量,并进行必要的更正。另外,NetBeans IDE还提供了用于调试和测试应用程序的工具,可帮助您查找和解决错误。 NetBeans IDE还具有许多插件和扩展,可以扩展其功能。您可以根据需要安装各种插件,例如版本控制系统插件、数据库工具插件等,以便更好地满足您的需求。您还可以根据自己的喜好和习惯进行个性化设置,例如更改主题、快捷键等。 总的来说,Apache NetBeans IDE 12.4是一个功能强大且易于使用的开发环境,适用于各种编程语言和技术。通过合理利用其功能和工具,您可以更加高效地开发应用程序,并提高代码的质量和可靠性。 ### 回答3: Apache NetBeans IDE 12.4是一种集成开发环境(IDE),专为Java开发人员设计。它是Apache软件基金会的项目,致力于提供一个强大且灵活的开发环境,以帮助开发人员更轻松地构建Java应用程序。 使用Apache NetBeans IDE 12.4,首先需要下载并安装该软件。安装完成后,启动NetBeans,并选择一个项目或创建一个新项目。NetBeans IDE提供了许多项目模板,可以选择适合您的项目类型的模板。然后,您可以通过添加文件、类和资源来构建项目的结构。 一旦项目结构设定完毕,您可以开始编写代码。NetBeans IDE提供了一个强大的代码编辑器,带有语法高亮,代码补全和导航等功能,以帮助您更有效地编写代码。您可以通过单击工具栏中的“运行”按钮来运行您的应用程序,并使用调试器来调试代码。 此外,NetBeans IDE还具有许多其他功能,如版本控制集成、自动构建工具和代码分析工具等。这些功能可以提高开发效率,并帮助您编写更高质量的代码。 对于初学者来说,NetBeans IDE提供了用户友好的界面和大量的帮助文档,使其更容易上手。您可以使用内置的帮助文档,查找和解决常见问题。还可以参考在线论坛和社区,与其他NetBeans用户交流和分享经验。 总而言之,Apache NetBeans IDE 12.4是一个功能强大且易于使用的开发环境,提供了丰富的功能和工具,帮助Java开发人员更高效地构建和调试应用程序。无论是初学者还是经验丰富的开发人员,都可以从NetBeans IDE中受益。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值