您当前的位置:首页 > 互联网教程

java如何创建一个简单的http接口

发布时间:2025-05-22 10:29:28    发布人:远客网络

java如何创建一个简单的http接口

一、java如何创建一个简单的http接口

1、在Java中创建一个简单的HTTP接口,可以通过Servlet实现。首先,在web.xml文件中添加相应的配置,指定Servlet的类名和映射路径。示例如下:

2、<!--配置SmsHTTPServer Servlet-->

3、<servlet-name>TestHTTPServer</servlet-name>

4、<servlet-class>com.atoz.http.SmsHTTPServer</servlet-class>

5、<servlet-name>TestHTTPServer</servlet-name>

6、<url-pattern>/httpServer</url-pattern>

7、接着,创建SmsHTTPServer.java文件,继承自HttpServlet类,实现doGet和doPost方法,处理HTTP请求。

8、在doGet方法中,设置响应内容类型,获取请求参数,检查参数是否为空。如果参数不为空,调用Spring框架的BeanFactory获取SendSMSAction对象,执行发送短信的操作,并输出成功信息。

9、doPost方法直接调用doGet方法处理POST请求。

10、发送HTTP请求时,可以使用URL类和BufferedReader类读取返回信息。示例如下:

11、content= URLEncoder.encode(content,"utf-8");

12、String url=""+ content+"&mobiles=15301895007";

13、in= new BufferedReader(new InputStreamReader(httpTest.openStream()));

14、while((inputLine= in.readLine())!= null)

15、} catch(MalformedURLException e){

16、// TODO Auto-generated catch block

17、以上就是创建一个简单的HTTP接口的详细步骤。

二、如何用java实现HTTP长连接

轮询:隔一段时间访问服务器,服务器不管有没有新消息都立刻返回。

package houlei.csdn.keepalive;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.net.UnknownHostException;

import java.util.concurrent.ConcurrentHashMap;

* C/S架构的客户端对象,持有该对象,可以随时向服务端发送消息。

*创建时间:2010-7-18上午12:17:25

*处理服务端发回的对象,可实现该接口。

public static interface ObjectAction{

void doAction(Object obj,Client client);

public static final class DefaultObjectAction implements ObjectAction{

public void doAction(Object obj,Client client){

System.out.println("处理:\t"+obj.toString());//诊断程序是否正常

public static void main(String[] args) throws UnknownHostException, IOException{

Client client= new Client(serverIp,port);

private boolean running=false;

private ConcurrentHashMap<Class, ObjectAction> actionMapping= new ConcurrentHashMap<Class,ObjectAction>();

public Client(String serverIp, int port){

this.serverIp=serverIp;this.port=port;

public void start() throws UnknownHostException, IOException{

socket= new Socket(serverIp,port);

System.out.println("本地端口:"+socket.getLocalPort());

lastSendTime=System.currentTimeMillis();

new Thread(new KeepAliveWatchDog()).start();

new Thread(new ReceiveWatchDog()).start();

*@param cls待处理的对象,其所属的类。

public void addActionMap(Class<Object> cls,ObjectAction action){

actionMapping.put(cls, action);

public void sendObject(Object obj) throws IOException{

ObjectOutputStream oos= new ObjectOutputStream(socket.getOutputStream());

System.out.println("发送:\t"+obj);

class KeepAliveWatchDog implements Runnable{

if(System.currentTimeMillis()-lastSendTime>keepAliveDelay){

Client.this.sendObject(new KeepAlive());

lastSendTime= System.currentTimeMillis();

} catch(InterruptedException e){

class ReceiveWatchDog implements Runnable{

InputStream in= socket.getInputStream();

ObjectInputStream ois= new ObjectInputStream(in);

System.out.println("接收:\t"+obj);//接受数据

ObjectAction oa= actionMapping.get(obj.getClass());

oa= oa==null?new DefaultObjectAction():oa;

oa.doAction(obj, Client.this);

package houlei.csdn.keepalive;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.util.concurrent.ConcurrentHashMap;

*创建时间:2010-7-18上午12:17:37

*要处理客户端发来的对象,并返回一个对象,可实现该接口。

public interface ObjectAction{

public static final class DefaultObjectAction implements ObjectAction{

public Object doAction(Object rev){

System.out.println("处理并返回:"+rev);//确认长连接状况

public static void main(String[] args){

Server server= new Server(port);

private volatile boolean running=false;

private long receiveTimeDelay=3000;

private ConcurrentHashMap<Class, ObjectAction> actionMapping= new ConcurrentHashMap<Class,ObjectAction>();

connWatchDog= new Thread(new ConnWatchDog());

@SuppressWarnings("deprecation")

if(connWatchDog!=null)connWatchDog.stop();

public void addActionMap(Class<Object> cls,ObjectAction action){

actionMapping.put(cls, action);

class ConnWatchDog implements Runnable{

ServerSocket ss= new ServerSocket(port,5);

new Thread(new SocketAction(s)).start();

class SocketAction implements Runnable{

long lastReceiveTime= System.currentTimeMillis();

public SocketAction(Socket s){

if(System.currentTimeMillis()-lastReceiveTime>receiveTimeDelay){

InputStream in= s.getInputStream();

ObjectInputStream ois= new ObjectInputStream(in);

lastReceiveTime= System.currentTimeMillis();

System.out.println("接收:\t"+obj);

ObjectAction oa= actionMapping.get(obj.getClass());

oa= oa==null?new DefaultObjectAction():oa;

ObjectOutputStream oos= new ObjectOutputStream(s.getOutputStream());

System.out.println("关闭:"+s.getRemoteSocketAddress());//关闭长连接

长连接的维持,是要客户端程序,定时向服务端程序,发送一个维持连接包的。

如果,长时间未发送维持连接包,服务端程序将断开连接。

三、如何用Java实现Web服务器

Web服务器基于HTTP协议进行数据传输,HTTP协议建立在TCP/IP协议之上,主要应用于Web浏览器与Web服务器之间的通信。它通过一系列的请求和应答过程来实现信息的交换。具体而言,HTTP协议包括四个步骤:连接、请求、应答和关闭连接。

首先,Web浏览器与Web服务器建立连接,打开一个称为socket的虚拟文件,这标志着连接成功。接着,Web浏览器通过socket向Web服务器提交请求。HTTP请求通常为GET或POST命令,GET命令格式为:GET路径/文件名 HTTP/1.0,其中文件名指所访问的文件,HTTP/1.0指Web浏览器使用的HTTP版本。

Web服务器收到请求后,处理事务并将结果通过HTTP协议传回给Web浏览器。例如,假设客户机与www.mycompany.com:8080/mydir/index.html建立了连接,就会发送GET命令:GET/mydir/index.html HTTP/1.0。主机名为www.mycompany.com的Web服务器从其文档空间搜索子目录mydir的文件index.html,找到该文件后,Web服务器将文件内容传送给相应的Web浏览器。

Web服务器会首先发送一些HTTP头信息,如HTTP 1.0 200 OK,这表明服务器正在运行的HTTP版本号和应答代码。接着,Web服务器会指示MIME类型,通常为text/html,这表明传送的数据是HTML文档。最后,Web服务器会告知Web浏览器HTTP体信息的长度,然后传送具体内容。

在应答结束后,Web浏览器与Web服务器必须断开连接,以确保其他Web浏览器能够与Web服务器建立连接。

在Java中实现Web服务器功能的程序设计,需要遵循上述HTTP协议的作用原理。具体实现方法如下:创建ServerSocket类对象,监听端口8080;等待、接受客户机连接到端口8080,得到与客户机连接的socket;创建与socket相关联的输入流instream和输出流outstream;从与socket关联的输入流instream中读取一行客户机提交的请求信息,解析请求信息以获取请求类型和文件名;如果请求类型为GET,则打开HTML文件,将HTTP头信息和HTML文件内容通过socket传回给Web浏览器;最后,关闭与相应Web浏览器连接的socket。

为了实现多线程,可以编写如下程序:

public static void main(String args[])

server=new ServerSocket(PORT);

System.out.println("Web Server is listening on port"+server.getLocalPort());

client=server.accept();//接受客户机的连接请求

new ConnectionThread(client, i).start();

catch(Exception e){System.out.println(e);}

/* ConnnectionThread类完成与一个Web浏览器的通信*/

class ConnectionThread extends Thread

Socket client;//连接Web浏览器的socket字

public ConnectionThread(Socket cl, int c)

String destIP=client.getInetAddress().toString();//客户机IP地址

int destport=client.getPort();//客户机端口号

System.out.println("Connection"+counter+": connected to"+destIP+" on port"+destport+".");

PrintStream outstream=new PrintStream(client.getOutputStream());

DataInputStream instream=new DataInputStream(client.getInputStream());

String inline=instream.readLine();//读取Web浏览器提交的请求信息

System.out.println("Received:"+inline);

if(getrequest(inline)){//如果是GET请求

String filename=getfilename(inline);

if(file.exists()){//若文件存在,则将文件送给Web浏览器

System.out.println(filename+" requested.");

outstream.println("HTTP/1.0 200 OK");

outstream.println("MIME_version:1.0");

outstream.println("Content_Type:text/html");

outstream.println("Content_Length:"+len);

sendfile(outstream, file);//发送文件

String notfound=" Error 404-file not found";

outstream.println("HTTP/1.0 404 no found");

outstream.println("Content_Type:text/html");

outstream.println("Content_Length:"+notfound.length()+2);

catch(Exception e){System.out.println(e);}

此程序实现了多线程,能够同时处理多个客户机的请求。