java httpserver api_http编程(一)使用javaAPI实现

Java Http编程中常见的实现方式是使用Java 提供的API,另外就是使用Apache提供的 API1、通过Java提供的API实现Http编程

类:URL:类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。

HttpURLConnection:支持 HTTP 特定功能的 URLConnection

URLConnection 抽象类是所有类的超类,它代表应用程序和 URL 之间的通信链接。此类的实例可用于读取和写入此 URL 引用的资源1.1、下载数据(以下载一直图片为例)importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.URL;public classDownloadImage {public static void main(String[] args) throwsIOException {//资源的URL:就是一个资源的连接,URL中的参数淡然也可以是网上的一些图片或者其他资源的连接了//例如把http://localhost:8080/Day_0818/aa.jpg换为http://home.cnblogs.com/images/logo_home.gif下载博客园的logo,当然存储 到时候要改后缀了

URL url = new URL("http://localhost:8080/Day_0818/aa.jpg");//通过url获取一个封装了http协议的URL连接对象:HttpURLConnection

HttpURLConnection connection =(HttpURLConnection) url.openConnection();//设置连接的请求方式,因为是获取数据,所以请求方式为GET:必须大写

connection.setRequestMethod("GET");//设置是否能够获取连接的输入流,默认就是true,也可以不写这条语句

connection.setDoInput(true);//有了连接,就要打开连接

connection.connect();//获取响应码

int code =connection.getResponseCode();//响应码是200则表示连接成功响应

if(200 ==code){//获取连接 的输入流

InputStream is =connection.getInputStream();//文件输出流对象,(创建存放资源的文件)

FileOutputStream fos = new FileOutputStream("e:\\aa.jpg");//字节数组,我理解为输入流和输出流的一个中介,输入流把数据放到数组里让输出流读取

byte[] b = new byte[1024];int length = -1;while((length = is.read(b)) != -1){

fos.write(b,0, length);

fos.flush();

}//关闭流

fos.close();

}

}

}

----------------------------------------------------------------------------------------//post方式来模拟登录。/*需要创建LoginServlet类接收数据*/

importjava.io.InputStream;importjava.io.OutputStream;importjava.net.HttpURLConnection;importjava.net.URL;//http://localhost:8080/MyServer/loginServlet?username=admin&userpwd=111

public classURLDemo2 {public static void main(String[] args) throwsException {

String path= "http://localhost:8080/MyServer/loginServlet";

URL url= newURL(path);

HttpURLConnection connection=(HttpURLConnection) url.openConnection();

connection.setRequestMethod("POST");

connection.setConnectTimeout(30000);

connection.setDoInput(true);

connection.setDoOutput(true);//username=admin&userpwd=111

/** 将用户名和密码改成用户输入的数据。*/OutputStream os=connection.getOutputStream();

os.write("username=admin&userpwd=111".getBytes());

connection.connect();int code =connection.getResponseCode();if(code==200){

InputStream is=connection.getInputStream();byte[] b = new byte[1024];int length =is.read(b);

System.out.println(new String(b,0,length));

is.close();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值