聊天机器人_远程接口javautil

本文介绍了一个实用的HTTP客户端工具类的实现,该工具类支持GET和DELETE请求,包括参数拼接、设置请求头和超时时间等功能。通过示例展示了如何使用此工具类发起HTTP请求并获取响应。

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

package com.httpdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

 
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientUtil {
	private static int DEFAULT_TIME_OUT = 5000;// 超时时间 单位毫秒
	protected static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	
	public static String get(String endurls,Map<String,Object> map) throws HttpException, IOException{
		return  get(endurls,map,null,DEFAULT_TIME_OUT);
		
	}
	 //拼接url
	private static String get(String endurls, Map<String, Object> map,Map<String, Object> headers, int timeOut) throws HttpException, IOException {
		 String result = null;//返回结果结合
		 HttpClient httpClient = new HttpClient();
		 httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 指定传送字符集为UTF-8格式
		 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);//设置超时时间
		 endurls+="?";
		 int start=0;
		 if(map != null){
			 for (Map.Entry<String, Object> entry:map.entrySet()) {
				 if(start == 0){
					 endurls=endurls +entry.getKey() +"="+entry.getValue();
				 }else{
					 endurls=endurls +"&"+entry.getKey() +"="+entry.getValue();
				 }
				 start++;
			}
		 }
		 System.out.println(endurls);
		 //方法处理一
		 String xmlresult=result( endurls);
		 //方法处理2
		return xmlresult;
	}
	//对网络地址进行处理
	private static String result (String endurls) throws IOException  {
		URL getUrl = new URL(endurls);
		HttpURLConnection connection =(HttpURLConnection)getUrl.openConnection();
		connection.connect();
		 // 取得输入流,并使用Reader读取
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
		StringBuffer sb = new StringBuffer();
		String line="";
		while ((line=reader.readLine())!= null) {
			sb.append(line);
		}
		reader.close();
		connection.disconnect();
		return sb.toString();
	}
	private static String result(String endurls,Map<String, Object> headers, HttpClient httpClient,String result) throws HttpException, IOException{
		 HttpMethod httpMethod =new GetMethod(endurls); 
		 if(null != headers){	//
			 for (Map.Entry<String, Object> entry:headers.entrySet()) {
				 httpMethod.addRequestHeader(entry.getKey(), entry.getValue().toString());
			}
		 }
		 //发送请求
		 int statusCode = httpClient.executeMethod(httpMethod);
		 // 请求状态不等200时不成功
		if(statusCode != HttpStatus.SC_OK){
			logger.error("网络连接异常,GET请求失败,请求地址:"+ endurls + "返回状态码:"+ statusCode);
			throw new HttpException("网络连接异常");
		}
		InputStream inputStream = httpMethod.getResponseBodyAsStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		String string = "";
		StringBuffer stringBuffer = new StringBuffer();
		while ((string=br.readLine())!= null) {
			stringBuffer.append(string);
		}
		inputStream.close();	//关流
		httpMethod.releaseConnection();//释放连接
		httpClient.getHttpConnectionManager().closeIdleConnections(0);
		result=stringBuffer.toString();
		return result;
		
	}
	public static String delete(String endurls, Map<String,Object> map,Map<String,String> headers,int timeOut) throws IOException, IOException{
		CloseableHttpClient client = HttpClientBuilder.create().build();
		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut).setConnectionRequestTimeout(timeOut).setSocketTimeout(timeOut).build();
		if(map != null){
			List<NameValuePair> nvps =new ArrayList<NameValuePair>();
			for (Map.Entry<String, Object> entry:map.entrySet()) {
				if(entry.getValue() != null && !"".equals(entry.getValue())){
					nvps.add(new BasicNameValuePair(entry.getKey(),  entry.getValue().toString()));
				}
				if(!nvps.isEmpty()){
					endurls += "?" +URLEncodedUtils.format(nvps, "utf-8");
				}
			}
		}
		HttpRequestBase request = new HttpDelete(endurls);
		request.setConfig(requestConfig);
		if(headers != null){
			Iterator<String> it = headers.keySet().iterator();
			while(it.hasNext()){
				String key = it.next();
				String value = headers.get(key);
				request.addHeader(key, value);
			}
		}
		CloseableHttpResponse response = client.execute(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) 
			return EntityUtils.toString(response.getEntity(),Charset.forName("UTF-8"));
		
		return "";
		
	}
	public static void main(String[] args) {
	String url="http://www.tuling123.com/openapi/api?key=b9c73434132c08a17a70eb977d743f3b&info=讲个故事";
	String endurls="http://www.tuling123.com/openapi/api";
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("key", "b9c73434132c08a17a70eb977d743f3b");
	map.put("info", "你叫什么名字");
		try {
			String result = HttpClientUtil.get(endurls, map);
			System.out.println(result);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

### Netty框架的基本概念 Netty 是一个高性能、异步事件驱动的网络应用程序框架,主要用于快速开发可维护的高性能协议服务器和客户端。它基于 Java NIO 构建,提供了一种高效的网络通信机制,适用于构建高并发、低延迟的网络服务[^1]。 Netty 的核心设计目标是简化网络编程,并提供高度可扩展性和灵活性。它通过封装底层网络操作,使开发者能够专注于业务逻辑的实现,而不是底层通信细节。其架构围绕 `Channel`、`EventLoop` 和 `ChannelHandler` 等关键组件展开,支持多种协议(如 TCP、UDP、HTTP、WebSocket 等)并允许自定义协议的实现[^3]。 --- ### Netty的核心功能 - **高性能**:Netty 使用异步非阻塞 I/O 模型,结合事件驱动机制,能高效处理大量并发连接。此外,它还采用零拷贝、内存池等优化策略来提升性能和吞吐量[^2]。 - **多协议支持**:Netty 提供了丰富的内置协议支持,包括 HTTP、WebSocket、FTP、SMTP 等常见协议,并且可以通过自定义编解码器实现专有协议交互[^3]。 - **灵活的编解码机制**:开发者可以使用 Netty 提供的 `Encoder` 和 `Decoder` 接口,轻松实现数据的序列化与反序列化,满足不同应用场景下的数据格式需求[^3]。 - **可扩展性与模块化**:Netty 的组件设计高度模块化,例如 `ChannelPipeline` 可以动态添加或移除处理器,便于构建可扩展的网络应用[^3]。 - **安全性支持**:Netty 集成了 SSL/TLS 协议,支持加密通信、身份验证等安全机制,确保数据传输的安全性。 - **跨平台能力**:作为基于 Java 的框架,Netty 可运行在 Windows、Linux、macOS 等多种操作系统平台上,具备良好的兼容性。 --- ### Netty的应用场景 Netty 被广泛应用于需要高性能网络通信的各类系统中,常见的使用场景包括: - **即时通讯系统**:如 IM 服务、聊天机器人等,利用 Netty 的异步非阻塞特性,能够支撑高并发的消息收发[^3]。 - **分布式系统通信**:在微服务架构中,Netty 常用于服务间通信、RPC 框架的数据传输层,保证低延迟和高可靠性。 - **游戏服务器开发**:由于其出色的并发处理能力和低延迟特性,Netty 成为构建在线游戏后端通信层的理想选择[^3]。 - **物联网设备通信**:Netty 支持 TCP、UDP、MQTT 等协议,适用于连接海量 IoT 设备并进行数据采集与控制[^3]。 - **远程调用与 RPC 框架**:许多流行的 RPC 框架(如 Dubbo、gRPC)底层都采用 Netty 作为网络通信层,保障服务间的高效调用[^3]。 --- ### 示例代码:Netty TCP Server 简单实现 以下是一个使用 Netty 实现的简单 TCP 服务端示例: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class NettyTcpServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new SimpleServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = bootstrap.bind(8080).sync(); future.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } } ``` 对应的处理器类: ```java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class SimpleServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf in = (ByteBuf) msg; try { System.out.println("Received: " + in.toString(io.netty.util.CharsetUtil.UTF_8)); } finally { in.release(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值