首页 > 其他分享 >httpclient

httpclient

时间:2023-12-31 13:11:38浏览次数:28  
标签:String url RequestConfig httpPost 1000 response httpclient

java-httpclient

1.maven

<!-- 主要的jar-->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.2</version>
</dependency>

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.18.10</version>
</dependency>

 <dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.3.2</version>
</dependency>

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.7</version>
</dependency>

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

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.41</version>
</dependency>

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.8.8</version>
</dependency>


2.实例

2.1 GET

public static String doGet(String url, Map<String, String> params) {
		String result = "";
        /**
		 * RequestConfig:
		 * setSocketTimeout: socket读取数据超时时间
		 * setConnectTimeout: 与服务器链接超时时间
		 * setConnectionRequestTimeout: 从连接池获取连接的超时时间
		 */
		RequestConfig reqConfig = RequestConfig.custom()
				.setSocketTimeout(60 * 1000)
				.setConnectTimeout(10 * 1000)
				.setConnectionRequestTimeout(10 * 1000)
				.build();

		/**
		 * HttpClientBuilder:
		 * setMaxConnTotal: 连接池最大连接数
		 * setMaxConnPerRoute: 分配给同一个路由最大的并发连接数
		 * setDefaultConfig(RequestConfig)
		 */
		HttpClient httpClient = HttpClientBuilder.create()
				.setDefaultRequestConfig(reqConfig)
				.build();
		HttpGet httpGet = null;
		try {
			URIBuilder uriBuilder = new URIBuilder(url);
			if (null != params && !params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					uriBuilder.addParameter(entry.getKey(), entry.getValue());
				}
			}
			URI uri = uriBuilder.build();
			httpGet = new HttpGet(uri);
			HttpResponse response = httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity());
				log.info("doGetSuccess({}):{}",url, result);
			} else {
				log.error("doGetFail({}):{}", url, response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			log.error("doGetError({}):{}", url, ExceptionUtils.getStackTrace(e));
		} finally {
			// 释放连接
			if (null != httpGet) {
				httpGet.releaseConnection();
			}
		}
		return result;
	}

2.2 POST-Common

public static String doPost(String url, Map<String, String> params) {
		String result = "";
		RequestConfig reqConfig = RequestConfig.custom()
				.setSocketTimeout(60 * 1000)
				.setConnectTimeout(10 * 1000)
				.setConnectionRequestTimeout(10 * 1000)
				.build();

		/**
		 * HttpClientBuilder:
		 * setMaxConnTotal: 连接池最大连接数
		 * setMaxConnPerRoute: 分配给同一个路由最大的并发连接数
		 * setDefaultConfig(RequestConfig)
		 */
		HttpClient httpClient = HttpClientBuilder.create()
				.setDefaultRequestConfig(reqConfig)
				.build();
		HttpPost httpPost = new HttpPost(url);
		try { // 参数键值对
			if (null != params && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<NameValuePair>();
				NameValuePair pair = null;
				for (String key : params.keySet()) {
					pair = new BasicNameValuePair(key, params.get(key));
					pairs.add(pair);
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
				httpPost.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
				log.info("doPostSuccess({}):{}",url, result);
			} else {
				log.error("doPostFail({}):{}", url, response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			log.error("doPostError({}):{}", url,ExceptionUtils.getStackTrace(e));
			e.printStackTrace();
		} finally {
			if (null != httpPost) {
				// 释放连接
				httpPost.releaseConnection();
			}
		}
		return result;
	}

2.3 POST-Json

public static String sendJson (String url, JSONObject jsonObject) {
		String result = "";

		/**
		 * RequestConfig:
		 * setSocketTimeout: socket读取数据超时时间
		 * setConnectTimeout: 与服务器链接超时时间
		 * setConnectionRequestTimeout: 从连接池获取连接的超时时间
		 */
		RequestConfig reqConfig = RequestConfig.custom()
				.setSocketTimeout(60 * 1000)
				.setConnectTimeout(10 * 1000)
				.setConnectionRequestTimeout(10 * 1000)
				.build();

		/**
		 * HttpClientBuilder:
		 * setMaxConnTotal: 连接池最大连接数
		 * setMaxConnPerRoute: 分配给同一个路由最大的并发连接数
		 * setDefaultConfig(RequestConfig)
		 */
		HttpClient httpClient = HttpClientBuilder.create()
				.setDefaultRequestConfig(reqConfig)
				.build();
		HttpPost httpPost = new HttpPost(url);
		try {
			httpPost.addHeader("Content-type", "application/json;charset=utf-8");
			httpPost.setHeader("Accept", "application/json");
			if (StringUtils.isNotBlank(jsonObject.toString())) {
				httpPost.setEntity(new StringEntity(jsonObject.toString(), StandardCharsets.UTF_8));
			}
			HttpResponse response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				if (entity != null){
//					result = EntityUtils.toString(entity, "utf-8");
					result = JSONObject.parseObject(EntityUtils.toString(entity, StandardCharsets.UTF_8)).toJSONString();
				}
			}else {
				log.error("sendJsonFail({}):{}",url, response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			log.error("sendJsonError({}):{}",url, ExceptionUtils.getStackTrace(e));
		}finally {
			if (null != httpPost) {
				// 释放连接
				httpPost.releaseConnection();
			}
		}
		return result;
	}

2.4 POST-File

public static String sendFilePost(String url, Map<String, ContentBody> reqParam){
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			// 创建http
			HttpPost httppost = new HttpPost(url);
			/**
			 * RequestConfig:
			 * setSocketTimeout: socket读取数据超时时间
			 * setConnectTimeout: 与服务器链接超时时间
			 * setConnectionRequestTimeout: 从连接池获取连接的超时时间
			 */
			RequestConfig reqConfig = RequestConfig.custom()
					.setSocketTimeout(60 * 1000)
					.setConnectTimeout(10 * 1000)
					.setConnectionRequestTimeout(10 * 1000)
					.build();
			httppost.setConfig(reqConfig);
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			multipartEntityBuilder.setCharset(StandardCharsets.UTF_8);
			for(Map.Entry<String,ContentBody> param : reqParam.entrySet()){
				multipartEntityBuilder.addPart(param.getKey(), param.getValue());
			}
			HttpEntity reqEntity = multipartEntityBuilder.build();
			httppost.setEntity(reqEntity);
			try {
				// 发起post请求
				response = httpclient.execute(httppost);
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				if (entity != null) {
//					return EntityUtils.toString(entity, StandardCharsets.UTF_8);
					// unicode转中文
					return JSONObject.parseObject(EntityUtils.toString(entity, StandardCharsets.UTF_8)).toJSONString();
				}
			} catch (IOException e){
				e.printStackTrace();
				log.error("请求-{}-响应异常:{}", url, String.valueOf(e));
			}
		} finally {
			// 关闭连接 释放资源
			try {
				if (response != null){
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
				log.error("请求-{}-内部异常:{}", url, String.valueOf(e));
			}
		}
		return null;
	}


标签:String,url,RequestConfig,httpPost,1000,response,httpclient
From: https://www.cnblogs.com/fsh19991001/p/17937423

相关文章

  • Java+SpringBoot+Maven+TestNG+httpclient+Allure+Jenkins实现接口自动化
    一、方案需求目标:测试左移,测试介入研发过程,验证单接口正常及异常逻辑选用工具:Java、SpringBoot、Maven、TestNG、httpclient、Allure、Jenkins方案:创建测试接口测试工程,参照研发设计文档和设计思路,编写正常及异常用例,直接调用服务端接口,覆盖接口逻辑和验证异常处理,提升接口健壮......
  • apache HttpClient异常-ProtocolException: Target host is not specified
    昨夜,甘肃临夏州积石山县发生6.2级地震,影响到甘肃、青海地区。截至目前,已有100多人遇难。百度了一下当地天气,还挺冷,夜间温度低到-15℃。时间就是生命,祈祷难民尽快得到救援!  分享今天解决的一个生产问题告警。如下HTTP工具类中的httpClientPost方法使用apache的HttpClient(maven坐标......
  • HttpClient5升级笔记--API篇
    最近终于是安奈不住升级的冲动,将自己项目的HttpClient版本从4升级到了5,其过程不可谓不艰辛,很多API改动让人无从下手。ApacheHttpClient5(也称为HttpClient5.x)是ApacheHttpComponents项目中的一个重要组件,用于发送HTTP请求和处理HTTP响应。它在与网络通信和处理方面提供......
  • Remove TraceParent header from HttpClient requests
    ASP.NETCorecreatesanActivitythatrepresentstherequestbydefault.ThisiswhattellsHttpClienttosendanoutgoingrequestidheader.Youcandisableitinacoupleofways:Bysettingthecurrentactivitytonullbeforemakingtherequest(Activi......
  • apache HttpClient异常-ProtocolException: Target host is not specified
    昨夜,甘肃临夏州积石山县发生6.2级地震,影响到甘肃、青海地区。截至目前,已有100多人遇难。百度了一下当地天气,还挺冷,夜间温度低到-15℃。时间就是生命,祈祷难民尽快得到救援!  分享今天解决的一个生产问题告警。如下HTTP工具类中的httpClientPost方法使用apache的HttpClient(ma......
  • 异步记录第三方接口调用日志的优雅实现(HttpClient+装饰者模式+异步线程池)
    对于第三方接口调用日志这个功能,笔者在工作中曾见过以下两种方式:Restemplate+装饰者模式+MQ实现网关监控+Feign拦截器+观察者模式实现其中观察者模式的实现是我最为佩服的设计,个人认为以上两种实现都显得略过臃肿,应该简化设计,让异步记录的实现更加简洁优雅,因此产生了这样......
  • httpclient跳过SSL证书验证的写法
    最近在请求https接口的时候,发生了异常:sun.security.validator.ValidatorException:PKIXpathbuildingfailed:sun.security.provider.certpath.SuncertPathBuilderException:unabletofindvalidcertificationpathtorequestedtarget无法找到到请求目标的有效证书路......
  • DELPHI WIn7下使用 NetHttpClient 请求HTPPS 网站
    转载自:WIn7下使用NetHttpClient请求HTPPS网站-EEEEEEEEEEEEEEEEEEE-博客园(cnblogs.com)WIn7下使用NetHttpClient请求HTPPS网站在WIN7下使用HttpClient会报以下两种错;1ServerCertificateInvalidornotpresent2Errorsendingdata:(12175)发生了安......
  • C# HttpClient 基本使用方式(一)
    .NetCore主要提供了HttpWebRequest,WebClient,HttpClient这三种访问web的方式,其中HttpWebRequest,WebClient都在官方被标注为已过时,如果没有特殊需求,一般情况下还是使用官方推荐的HttpClient方式。HttpClient的基本使用方法使用HttpClient发送请求一般是如下几步:1.创建HttpClien......
  • Java使用HttpClient实现GET和POST请求
    GET请求(带参数)前端exportconstgetRealTimeData=(deviceLabel)=>{returnrequest({url:'/blade-inorganization/Data/realTime-data?deviceLabel='+deviceLabel,method:'get',})}import{getRealTimeData}from"@/api/......