HttpClient-HttpClient4.5使用代理服务器访问外网

前言: 当你处于公司内网无法对外网的接口访问,但是我们有一些第三方的接口处于外网,所以这个时候就需要配置代理服务器发出请求达到我们想要的目的。

通过代理服务器访问外网:
通过HttpClient官网提供的文档,发现HttpClient4.5的代理服务器做如下配置(附上HttpClient官网提供的文档的地址) --------官网地址

public static String postHttp(String url,String timestamp,String sign) {
		String result = "";
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse res = null;
		try {

			HttpClientContext context = HttpClientContext.create();
			// 创建一个httpClient对象
			httpclient = HttpClients.createDefault();
			//登陆 从配置文件中读取url(也可以写成参数)
			HttpPost httpPost = new HttpPost(url); 
			// 设置代理HttpHost
            HttpHost proxy = new HttpHost("****", 8080, "http");
            // 设置认证
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            // 添加代理用户认证-用户名和密码
            credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("****","****"));
            HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
            RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
			// 设置参数
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("timestamp", timestamp));
			formparams.add(new BasicNameValuePair("sign", sign));
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httpPost.setEntity(uefEntity);
			httpPost.setConfig(config);
			// 得到响应状态码
			res = httpclient.execute(httpPost,context);
			//  获取返回对象
			HttpEntity entity = res.getEntity();
			// 通过EntityUtils获取返回结果内容
			result = EntityUtils.toString(entity);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//  最后一定要释放资源
			if(httpclient!=null) {
				try {
					httpclient.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值