javase_23(Http的学习)

来源:互联网 发布:nginx 域名绑定 编辑:程序博客网 时间:2024/06/05 13:42

Http:学习

获得客户端发送过来的请求信息:

package com.javami.kudyDemo.HttpStudy;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class MyServer{public static void main(String[]args) throws IOException, InterruptedException{ServerSocket ss = new ServerSocket(8888);Socket socket = ss.accept();InputStream ips = socket.getInputStream();OutputStream ops = socket.getOutputStream();Thread.sleep(100);//让其完全的写入数据的时候.才读.int len = ips.available();byte [] buf = new byte[len];ips.read(buf);String data = new String(buf);System.out.println(data);ops.write("连接成功".getBytes());//让期休息一下才关闭流Thread.sleep(100);ss.close();}}
GET / HTTP/1.1Host: 127.0.0.1:8888Connection: keep-aliveAccept: */*Accept-Language: zh-cnUser-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)Accept-Encoding: gzip,deflateAccept-Charset: GBK,utf-8;q=0.7,*;q=0.3


 

如何去获取到服务器反馈回来的信息:

首先前提:我们必须要发送信息.才得以返回  使用到了xp自带的telNet命令(注:使用了TomCat)
 

GET /a.html HTTP/1.1Host:回车 再回车GET /a.html HTTP/1.1Host:      HTTP/1.1 400 Bad Request  Server: Apache-Coyote/1.1  Transfer-Encoding: chunked  Date: Tue, 04 Sep 2012 13:24:03 GMT  Connection: close


如何去获取到一个sina.com的内容,包括页面和配置信息-->集合要多加复习..

package com.javami.kudyDemo.HttpStudy;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.URL;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;public class SinaUrlTest{/** * 连接服务器 * @throws IOException  */public static void main(String[] args) throws IOException{//试图连接服务器URL url = new URL("http://www.sina.com.cn:80");//连接服务器HttpURLConnection sina = (HttpURLConnection) url.openConnection();//要类型转//设置请求头sina.setRequestMethod("GET");sina.setRequestProperty("Accept-Language","zh-cn" );sina.setRequestProperty("Connection", "Keep-Alive");//查看请求信息Map requests = sina.getRequestProperties();Set keys = requests.keySet();//获取到所有的SetIterator it = keys.iterator();//把set集合里面的内容放到迭代器里面迭代System.out.println("查看请求信息");while(it.hasNext()){String key = (String)it.next();String value = sina.getRequestProperty(key);//通过key找到valueSystem.out.println(key+"..."+value);}//查看服务器sina.connect();//查看服务器的相应信息:System.out.println("服务器反馈过来的信息:");Map<String,List<String>> responses = sina.getHeaderFields();//获取信息Set<String> responseKeys = responses.keySet();//获取到set里面的内容for(String key : responseKeys){String value = sina.getHeaderField(key);//通过key找到valieSystem.out.println(key +"===="+value);}//上面内容是如何去获取到配置信息的.集合内容一定需要复习啊``~~//查看页面File file = new File("src/网页内容.txt");InputStream ips =  sina.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(ips));BufferedWriter bw =new BufferedWriter(new FileWriter(file));String line;while((line=br.readLine())!=null){bw.write(line);bw.newLine();}ips.close();bw.close();}}


 

测试的内容如下:

http://127.0.0.1:8888/a.html

其实Thread.sleep()用处不少.假设我们这边读取数据.必须等待一下.让其上面的程序都执行完毕.考虑在实际的场景去应用.

package com.javami.kudyDemo.HttpStudy;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class HttpServer{/** * 实现基于Http协议服务器程序 * 接收请求信息 */public static void main(String[] args){ServerSocket ss = null;int port ;try{port = Integer.parseInt(args[0]);}catch(RuntimeException e){port = 8888;System.out.println("该端口不可用,已经为您设置了默认的端口:"+port);}try{ss = new ServerSocket(port);while(true){Socket socket = ss.accept();new Thread(new HttpServers(socket)).start();}}catch(IOException e){e.printStackTrace();}finally{try{if(ss!=null)ss.close();}catch(IOException e){e.printStackTrace();}}}}使用多线程解决的问题:package com.javami.kudyDemo.HttpStudy;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;public class HttpServers implements Runnable{Socket socket ;public HttpServers(Socket socket){this.socket = socket;}public void run(){try{Thread.sleep(100);InputStream ips = socket.getInputStream();OutputStream ops = socket.getOutputStream();int len = ips.available();byte [] buf = new byte[len];ips.read(buf);String request = new String(buf,0,len);//获得请求的信息.System.out.println(request);//获取第一行的内容String firstLine = request.substring(0, request.indexOf("\r\n"));//到换行的地方结束String[] parts = firstLine.split(" ");String urlName = parts[1];//a.html//如果没有资源名,默认加上index.htmlif(urlName.length()==1)urlName+="index.html";//编写响应头int stuts = 200;String info = "ok";//创建对象-->判断是否是标准文件File file = new File("src/com/javami/kudyDemo/HttpStudy"+urlName); //如果找不到这个文件它有什么提示?if(!file.isFile()){stuts = 404;info = "file not found";}//还需要判断这一个文件的类型String connectionType;if(file.getName().endsWith(".html")||file.getName().endsWith("htm"))connectionType = "Text/html";else if(file.getName().endsWith(".jpg")||file.getName().endsWith(".jpeg"))connectionType = "image/jpeg";else if(file.getName().endsWith(".gif"))connectionType = "image/gif";elseconnectionType = "I say";//判断长度long connectionLength = file.length();//获取到文件的长度//发送相应回去的信息String response = "Http1.1"+stuts+" "+info+"\r\n"+ "Content-Length:" + connectionLength + "\r\n\r\n";//两个回车代表相应信息结束//发送响应的信息ops.write(response.getBytes());//发送文件的数据if(stuts==200)sendFile(file,ops);elseops.write("404,你懂的".getBytes());}catch(Exception e){e.printStackTrace();}finally{if(socket!=null)try{socket.close();} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}}}private void sendFile(File file, OutputStream ops) throws IOException{BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));BufferedOutputStream bos = new BufferedOutputStream(ops);//输出也给它包装一下int ch;while((ch=bis.read())!=-1){bos.write(ch);}bos.flush();bis.close();bos.close();}}


 

个人心得明天要复习单词,.把程序都复习一次.7点起床.,今天蛮不错的.kudy

 

 

原创粉丝点击