httpClient直连调用post接口

本文介绍了一种通过Java后端调用远程POST接口的方法,有效解决了前端开发中常见的跨域请求问题。提供了实用的工具类代码,实现简单且易于维护。

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

 今天在开发的时候发现用前端ajax调用其他机器的post接口请求的时候发现一直存在跨域请求问题,本来想用nginx代理解决跨域问题,后来又发现接口又有多个,代理麻烦,后期还要增加,后来就发现可以用java后端调用远程接口,并将返回来的结果返回给页面,这样就完美的解决了,直接赋上工具类
 
	
  public Class ClientUtil {

	/**
	  * 接口调用
	  * @param url 接口地址 json 为参数 参考(gson.getInstance.toJson(new HashMap("参数名","参数值")))需要转换     * 成json串格式的
	  */
	public static String doClient(String url,String json) {
		return doPost(url,json);
	
	
	}	
	
	/**
	 * 获取连接
	 * @return CloseableHttpClient对象
	 */
	public CloseableHttpClient buildHttpClient(){
		CloseableHttpClient client = null;
		HttpClientBuilder build = HttpClients.custom();  
		client = build.build();  
		return client;
	}
	
	/**
	 * 进行Post请求
	 * @param url 服务地址
	 * @param json 添加json串
	 * @return String结果
	 */
	public String doPost(String url,String json){
		CloseableHttpClient httpClient = buildHttpClient();
		HttpPost httpPost = new HttpPost(url);
		String result = null;
		try {
			httpPost.setHeader("content-type", "application/json;charset=UTF-8");//
			StringEntity se = new StringEntity(json,"utf-8");
		    httpPost.setEntity(se);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (ClientProtocolException e) {
			//logger.error("进行模拟HTTP请求时候发生异常 ,请求地址"+url,e);
		} catch (UnsupportedEncodingException e) {
			//logger.error("进行模拟HTTP请求时候发生异常,请求地址"+url,e);
		} catch (Exception e) {
			//logger.error("进行模拟HTTP请求时候发生异常,请求地址"+url,e);
		} finally {
			// 关闭连接,释放资源    
            try {httpClient.close();  }catch (IOException e) {e.printStackTrace(); }  
		}
		return result;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值