1. package cn.cctv.net;  

  2. import java.io.ByteArrayOutputStream;  

  3. import java.io.File;  

  4. import java.io.FileOutputStream;  

  5. import java.io.InputStream;  

  6. import java.net.HttpURLConnection;  

  7. import java.net.URL;  

  8. publicclass ImageRequest {  

  9. /**

  10.     * @param args

  11.     */

  12. publicstaticvoid main(String[] args) throws Exception {  

  13. //new一个URL对象

  14.        URL url = new URL("http://img.hexun.com/2011-06-21/130726386.jpg");  

  15. //打开链接

  16.        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  

  17. //设置请求方式为"GET"

  18.        conn.setRequestMethod("GET");  

  19. //超时响应时间为5秒

  20.        conn.setConnectTimeout(5 * 1000);  

  21. //通过输入流获取图片数据

  22.        InputStream inStream = conn.getInputStream();  

  23. //得到图片的二进制数据,以二进制封装得到数据,具有通用性

  24. byte[] data = readInputStream(inStream);  

  25. //new一个文件对象用来保存图片,默认保存当前工程根目录

  26.        File p_w_picpathFile = new File("BeautyGirl.jpg");  

  27. //创建输出流

  28.        FileOutputStream outStream = new FileOutputStream(p_w_picpathFile);  

  29. //写入数据

  30.        outStream.write(data);  

  31. //关闭输出流

  32.        outStream.close();  

  33.    }  

  34. publicstaticbyte[] readInputStream(InputStream inStream) throws Exception{  

  35.        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  

  36. //创建一个Buffer字符串

  37. byte[] buffer = newbyte[1024];  

  38. //每次读取的字符串长度,如果为-1,代表全部读取完毕

  39. int len = 0;  

  40. //使用一个输入流从buffer里把数据读取出来

  41. while( (len=inStream.read(buffer)) != -1 ){  

  42. //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度

  43.            outStream.write(buffer, 0, len);  

  44.        }  

  45. //关闭输入流

  46.        inStream.close();  

  47. //把outStream里的数据写入内存

  48. return outStream.toByteArray();  

  49.    }  

  50. }  

*************************************************************************************


Http学习之使用HttpURLConnection发送post和get请求

27245人阅读 评论(13) 收藏 举报
最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
在Java中可以使用HttpURLConnection发起这两种请求,了解此类,对于了解soap,和编写servlet的自动测试代码都有很大的帮助。
下面的代码简单描述了如何使用HttpURLConnection发起这两种请求,以及传递参数的方法:
ExpandedBlockStart.gif ContractedBlock.gif public class HttpInvoker ... {
InBlock.gif
InBlock.gif
publicstaticfinal String GET_URL ="http://localhost:8080/welcome1";
InBlock.gif
InBlock.gif
publicstaticfinal String POST_URL ="http://localhost:8080/welcome1";
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
publicstaticvoid readContentFromGet() throws IOException ...{
InBlock.gif
// 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码
InBlock.gif
       String getURL = GET_URL +"?username="
InBlock.gif
+ URLEncoder.encode("fat man", "utf-8");
InBlock.gif        URL getUrl
=new URL(getURL);
InBlock.gif
// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
InBlock.gif
// 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
InBlock.gif
       HttpURLConnection connection = (HttpURLConnection) getUrl
InBlock.gif                .openConnection();
InBlock.gif
// 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
InBlock.gif
// 服务器
InBlock.gif
       connection.connect();
InBlock.gif
// 取得输入流,并使用Reader读取
InBlock.gif
       BufferedReader reader =new BufferedReader(new InputStreamReader(
InBlock.gif                connection.getInputStream()));
InBlock.gif        System.out.println(
"=============================");
InBlock.gif        System.out.println(
"Contents of get request");
InBlock.gif        System.out.println(
"=============================");
InBlock.gif        String lines;
ExpandedSubBlockStart.gifContractedSubBlock.gif
while ((lines = reader.readLine()) !=null) ...{
InBlock.gif            System.out.println(lines);
ExpandedSubBlockEnd.gif        }

InBlock.gif        reader.close();
InBlock.gif
// 断开连接
InBlock.gif
       connection.disconnect();
InBlock.gif        System.out.println(
"=============================");
InBlock.gif        System.out.println(
"Contents of get request ends");
InBlock.gif        System.out.println(
"=============================");
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
publicstaticvoid readContentFromPost() throws IOException ...{
InBlock.gif
// Post请求的url,与get不同的是不需要带参数
InBlock.gif
       URL postUrl =new URL(POST_URL);
InBlock.gif
// 打开连接
InBlock.gif
       HttpURLConnection connection = (HttpURLConnection) postUrl
InBlock.gif                .openConnection();
InBlock.gif
// Output to the connection. Default is
InBlock.gif
// false, set to true because post
InBlock.gif
// method must write something to the
InBlock.gif
// connection
InBlock.gif
// 设置是否向connection输出,因为这个是post请求,参数要放在
InBlock.gif
// http正文内,因此需要设为true
InBlock.gif
       connection.setDoOutput(true);
InBlock.gif
// Read from the connection. Default is true.
InBlock.gif
       connection.setDoInput(true);
InBlock.gif
// Set the post method. Default is GET
InBlock.gif
       connection.setRequestMethod("POST");
InBlock.gif
// Post cannot use caches
InBlock.gif
// Post 请求不能使用缓存
InBlock.gif
       connection.setUseCaches(false);
InBlock.gif
// This method takes effects to
InBlock.gif
// every instances of this class.
InBlock.gif
// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
InBlock.gif
// connection.setFollowRedirects(true);
InBlock.gif
InBlock.gif
// This methods only
InBlock.gif
// takes effacts to this
InBlock.gif
// instance.
InBlock.gif
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
InBlock.gif
       connection.setInstanceFollowRedirects(true);
InBlock.gif
// Set the content type to urlencoded,
InBlock.gif
// because we will write
InBlock.gif
// some URL-encoded content to the
InBlock.gif
// connection. Settings above must be set before connect!
InBlock.gif
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
InBlock.gif
// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
InBlock.gif
// 进行编码
InBlock.gif
       connection.setRequestProperty("Content-Type",
InBlock.gif
"application/x-www-form-urlencoded");
InBlock.gif
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
InBlock.gif
// 要注意的是connection.getOutputStream会隐含的进行connect。
InBlock.gif
       connection.connect();
InBlock.gif        DataOutputStream out
=new DataOutputStream(connection
InBlock.gif                .getOutputStream());
InBlock.gif
// The URL-encoded contend
InBlock.gif
// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
InBlock.gif
       String content ="firstname="+ URLEncoder.encode("一个大肥人", "utf-8");
InBlock.gif
// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
InBlock.gif
       out.writeBytes(content);
InBlock.gif
InBlock.gif        out.flush();
InBlock.gif        out.close();
// flush and close
InBlock.gif
       BufferedReader reader =new BufferedReader(new InputStreamReader(
InBlock.gif                connection.getInputStream()));
InBlock.gif        String line;
InBlock.gif        System.out.println(
"=============================");
InBlock.gif        System.out.println(
"Contents of post request");
InBlock.gif        System.out.println(
"=============================");
ExpandedSubBlockStart.gifContractedSubBlock.gif
while ((line = reader.readLine()) !=null) ...{
InBlock.gif            System.out.println(line);
ExpandedSubBlockEnd.gif        }

InBlock.gif        System.out.println(
"=============================");
InBlock.gif        System.out.println(
"Contents of post request ends");
InBlock.gif        System.out.println(
"=============================");
InBlock.gif        reader.close();
InBlock.gif        connection.disconnect();
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
/** *//**
InBlock.gif     *
@param args
ExpandedSubBlockEnd.gif
*/
ExpandedSubBlockStart.gifContractedSubBlock.gif
publicstaticvoid main(String[] args) ...{
InBlock.gif
// TODO Auto-generated method stub
ExpandedSubBlockStart.gifContractedSubBlock.gif
try...{
InBlock.gif            readContentFromGet();
InBlock.gif            readContentFromPost();
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
catch (IOException e) ...{
InBlock.gif
// TODO Auto-generated catch block
InBlock.gif
           e.printStackTrace();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}

上面的 readContentFromGet()函数产生了一个get请求,传给servlet一个username参数,值为"fat man"。
readContentFromPost()函数产生了一个post请求,传给servlet一个firstname参数,值为"一个大肥人"。
HttpURLConnection.connect函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。无论是post还是get,http请求实际上直到 HttpURLConnection .getInputStream()这个函数里面才正式发送出去。

readContentFromPost()中,顺序是重中之重,对connection对象的一切配置(那一堆set函数)都必须要在connect()函数执行之前完成。而对outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。

http请求实际上由两部分组成,一个是http头,所有关于此次http请求的配置都在http头里面定义,一个是正文content,在connect()函数里面,会根据HttpURLConnection对象的配置值生成http头,因此在调用connect函数之前,就必须把所有的配置准备好。

紧接着http头的是http请求的正文,正文的内容通过outputStream写入,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,而是在流关闭后,根据输入的内容生成http正文。

至此,http请求的东西已经准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。由于http请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)都是没有意义的了,执行这些操作会导致异常的发生。  

************************************************************************************

Http学习之使用HttpURLConnection发送post请求深入

4488人阅读 评论(0) 收藏 举报
接上节 Http学习之使用HttpURLConnection发送post和get请求

本节深入学习post请求。

上节说道,post请求的OutputStream实际上不是网络流,而是写入内存,在getInputStream中才真正把写道流里面的内容作为正文与根据之前的配置生成的http request头合并成真正的http request,并在此时才真正向服务器发送。

HttpURLConnection.setChunkedStreamingMode函数可以改变这个模式,设置了ChunkedStreamingMode后,不再等待OutputStream关闭后生成完整的http request一次过发送,而是先发送http request头,正文内容则是网路流的方式实时传送到服务器。实际上是不告诉服务器http正文的长度,这种模式适用于向服务器传送较大的或者是不容易获取长度的数据,如文件。下面以一段代码讲解一下,请与 Http学习之使用HttpURLConnection发送post和get请求中的readContentFromPost()函数作对比:
ExpandedBlockStart.gif ContractedBlock.gif public static void readContentFromChunkedPost() throws IOException ... {
InBlock.gif        URL postUrl
=new URL(POST_URL);
InBlock.gif        HttpURLConnection connection
= (HttpURLConnection) postUrl
InBlock.gif                .openConnection();
InBlock.gif        connection.setDoOutput(
true);
InBlock.gif        connection.setDoInput(
true);
InBlock.gif        connection.setRequestMethod(
"POST");
InBlock.gif        connection.setUseCaches(
false);
InBlock.gif        connection.setInstanceFollowRedirects(
true);
InBlock.gif        connection.setRequestProperty(
"Content-Type",
InBlock.gif
"application/x-www-form-urlencoded");
ExpandedSubBlockStart.gifContractedSubBlock.gif
/**//*
InBlock.gif         * 与readContentFromPost()最大的不同,设置了块大小为5字节
ExpandedSubBlockEnd.gif
*/
InBlock.gif        connection.setChunkedStreamingMode(
5);
InBlock.gif        connection.connect();
ExpandedSubBlockStart.gifContractedSubBlock.gif
/**//*
InBlock.gif         * 注意,下面的getOutputStream函数工作方式于在readContentFromPost()里面的不同
InBlock.gif         * 在readContentFromPost()里面该函数仍在准备http request,没有向服务器发送任何数据
InBlock.gif         * 而在这里由于设置了ChunkedStreamingMode,getOutputStream函数会根据connect之前的配置
InBlock.gif         * 生成http request头,先发送到服务器。
ExpandedSubBlockEnd.gif
*/
InBlock.gif        DataOutputStream out
=new DataOutputStream(connection
InBlock.gif                .getOutputStream());
InBlock.gif        String content
="firstname="+ URLEncoder.encode("一个大肥人                                                                               "+
InBlock.gif
""+
InBlock.gif
"asdfasfdasfasdfaasdfasdfasdfdasfs", "utf-8");
InBlock.gif        out.writeBytes(content);
InBlock.gif
InBlock.gif        out.flush();
InBlock.gif        out.close();
// 到此时服务器已经收到了完整的http request了,而在readContentFromPost()函数里,要等到下一句服务器才能收到http请求。
InBlock.gif
       BufferedReader reader =new BufferedReader(new InputStreamReader(
InBlock.gif                connection.getInputStream()));
InBlock.gif
InBlock.gif        out.flush();
InBlock.gif        out.close();
// flush and close
InBlock.gif
       String line;
InBlock.gif        System.out.println(
"=============================");
InBlock.gif        System.out.println(
"Contents of post request");
InBlock.gif        System.out.println(
"=============================");
ExpandedSubBlockStart.gifContractedSubBlock.gif
while ((line = reader.readLine()) !=null) ...{
InBlock.gif            System.out.println(line);
ExpandedSubBlockEnd.gif        }

InBlock.gif        System.out.println(
"=============================");
InBlock.gif        System.out.println(
"Contents of post request ends");
InBlock.gif        System.out.println(
"=============================");
InBlock.gif        reader.close();
InBlock.gif        connection.disconnect();
ExpandedBlockEnd.gif    }

***********************************************************************************

HTTP Server的简易实现

761人阅读 评论(0) 收藏 举报
这里实现了一个最最简单的HTTP  server,只能处理GET请求,不能处理表单数据,没有完善的异常处理,单线程, 哈哈,不过基本框架是有了,功能很简单,设定一个工作目录,一个当页面找不到的时候返回的404页面,和监听端口。
根据GET请求的路径信息和设定的工作目录拼成页面文件的物理路径,去读取页面并返回,如果该路径指向的文件不存在,或者不为html文件,则返回404页面,如果是非法的请求(如POST)则直接干掉连接 wink_smile.gif嘻嘻。
具体代码如下:
ExpandedBlockStart.gif ContractedBlock.gif /** */ /**
InBlock.gif *
ExpandedBlockEnd.gif
*/
None.gif
package org.hello.server;
None.gif
None.gif
import java.io.BufferedReader;
None.gif
import java.io.DataOutputStream;
None.gif
import java.io.File;
None.gif
import java.io.FileInputStream;
None.gif
import java.io.IOException;
None.gif
import java.io.InputStream;
None.gif
import java.io.InputStreamReader;
None.gif
import java.io.OutputStream;
None.gif
import java.net.ServerSocket;
None.gif
import java.net.Socket;
None.gif
import java.nio.charset.Charset;
None.gif
import java.util.Date;
ExpandedBlockStart.gifContractedBlock.gif
/** */ /**
InBlock.gif *
@author pandazxx
InBlock.gif *
ExpandedBlockEnd.gif
*/
ExpandedBlockStart.gifContractedBlock.gif
public class SimpleHttpGetServer ... {
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
/** *//**
InBlock.gif     * html 文件存放的根路径
ExpandedSubBlockEnd.gif
*/
InBlock.gif
privatestaticfinal String ROOT_PATH ="/home/pandazxx/http/";
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
/** *//**
InBlock.gif     * 默认的字符编码
ExpandedSubBlockEnd.gif
*/
InBlock.gif
privatestaticfinal String DEFAULT_CHARSET = Charset.defaultCharset().name();
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
/** *//**
InBlock.gif     * 404页面的存放路径,这个路径一定要存在,因为程序偷懒没再判断了
ExpandedSubBlockEnd.gif
*/
InBlock.gif
privatestaticfinal String NOT_FOUND_PAGE_PATH ="/home/pandazxx/http/not_found.html";
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
/** *//**
InBlock.gif     * 默认监听端口
ExpandedSubBlockEnd.gif
*/
InBlock.gif
privatestaticfinalint DEFAULT_PORT =8080;
InBlock.gif
InBlock.gif
private ServerSocket server =null;
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
publicvoid start(int port) throws IOException ...{
InBlock.gif        server
=new ServerSocket(port);
InBlock.gif        Socket connection
=null;
ExpandedSubBlockStart.gifContractedSubBlock.gif
while (true) ...{
InBlock.gif            connection
= server.accept();
ExpandedSubBlockStart.gifContractedSubBlock.gif
try...{
InBlock.gif
InBlock.gif                String filepath
= ROOT_PATH
InBlock.gif
+ readGetRequest(connection.getInputStream());
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
if (checkFile(filepath)) ...{
InBlock.gif                    OutputStream os
= connection.getOutputStream();
InBlock.gif                    writeHTTPResponseHeader(os, getFileSize(filepath));
InBlock.gif                    writeFileContent(os, filepath);
InBlock.gif                    os.close();
ExpandedSubBlockStart.gifContractedSubBlock.gif                }
else...{
InBlock.gif                    OutputStream os
= connection.getOutputStream();
InBlock.gif                    writeHttpNotFound(os, NOT_FOUND_PAGE_PATH);
ExpandedSubBlockEnd.gif                }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif            }
catch (HttpServerException e) ...{
InBlock.gif
// TODO 增加向客户端返回异常信息的代码。
ExpandedSubBlockStart.gifContractedSubBlock.gif
           }finally...{
InBlock.gif                connection.close();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
privatevoid writeHttpNotFoundContent(OutputStream os, String filepath) throws IOException ...{
InBlock.gif        FileInputStream fis
=new FileInputStream(filepath);
InBlock.gif
byte[] buffer =newbyte[2048];
InBlock.gif
int readCnt =-1;
ExpandedSubBlockStart.gifContractedSubBlock.gif
while ((readCnt = fis.read(buffer)) !=-1) ...{
InBlock.gif            os.write(buffer,
0, readCnt);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
privatevoid writeHttpNotFound(OutputStream os, String filepath) throws IOException ...{
InBlock.gif        DataOutputStream dos
=new DataOutputStream(os);
InBlock.gif
InBlock.gif        String notFoundHeader
="HTTP/1.1 404 Not Found "
InBlock.gif
+"Date: "+new Date() +""
InBlock.gif
+"Server: SimpleHttpGetServer "
InBlock.gif
+"Content-Type: text/html "
InBlock.gif
+"Content-Length: "+ getFileSize(filepath) +""
InBlock.gif
+"";
InBlock.gif        dos.writeBytes(notFoundHeader);
InBlock.gif        writeHttpNotFoundContent(os, filepath);
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
privatelong getFileSize(String filepath) ...{
InBlock.gif        File file
=new File(filepath);
InBlock.gif
return file.length();
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
privatevoid writeFileContent(OutputStream os, String filepath) throws IOException ...{
InBlock.gif        FileInputStream fis
=new FileInputStream(filepath);
InBlock.gif
byte[] buffer =newbyte[2048];
InBlock.gif
int readCnt =-1;
ExpandedSubBlockStart.gifContractedSubBlock.gif
while ((readCnt = fis.read(buffer)) !=-1) ...{
InBlock.gif            os.write(buffer,
0, readCnt);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
privatevoid writeHTTPResponseHeader(OutputStream os, long contentSize) throws IOException ...{
InBlock.gif        DataOutputStream dos
=new DataOutputStream(os);
InBlock.gif        String repHeader
="HTTP/1.1 200 OK "
InBlock.gif
+"Date: "+new Date() +""
InBlock.gif
+"Server: SimpleHttpGetServer "
InBlock.gif
+"Content-Type: text/html;charset="+ DEFAULT_CHARSET +""
InBlock.gif
+"Content-Length: "+ contentSize +""
InBlock.gif
+"";
InBlock.gif        dos.writeBytes(repHeader);
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
privateboolean fileIsHTML(String filepath) ...{
InBlock.gif        String lowerName
= filepath.toLowerCase();
ExpandedSubBlockStart.gifContractedSubBlock.gif
if (lowerName.endsWith(".html") || lowerName.endsWith(".htm")) ...{
InBlock.gif
returntrue;
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
else...{
InBlock.gif
returnfalse;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
privateboolean checkFile(String filepath) ...{
ExpandedSubBlockStart.gifContractedSubBlock.gif
if (!fileIsHTML(filepath)) ...{
InBlock.gif
returnfalse;
ExpandedSubBlockEnd.gif        }

InBlock.gif        File file
=new File(filepath);
ExpandedSubBlockStart.gifContractedSubBlock.gif
if (!file.canRead()) ...{
InBlock.gif
returnfalse;
ExpandedSubBlockEnd.gif        }

InBlock.gif
returntrue;
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
/** *//**
InBlock.gif     * 偷懒之作,此函数仅仅是判断HTTP Request头是否GET的,获取Get的路径,其余信息一概不管。
InBlock.gif     *
@param is Input stream for the http connection.
InBlock.gif     *
@return The file path of the Get request
InBlock.gif     *
@throws IOException
InBlock.gif     *
@throws HttpServerException
ExpandedSubBlockEnd.gif
*/
InBlock.gif
private String readGetRequest(InputStream is) throws IOException,
ExpandedSubBlockStart.gifContractedSubBlock.gif            HttpServerException
...{
InBlock.gif        String filename
=null;
InBlock.gif        BufferedReader reader
=new BufferedReader(new InputStreamReader(is));
InBlock.gif        String line
= reader.readLine();
ExpandedSubBlockStart.gifContractedSubBlock.gif
if (line ==null) ...{
InBlock.gif
thrownew HttpServerException("Bad get request");
ExpandedSubBlockEnd.gif        }

InBlock.gif        filename
= parseGetRequest(line);
InBlock.gif
//is.close();
InBlock.gif
return filename;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif
private String parseGetRequest(String getRequest)
ExpandedSubBlockStart.gifContractedSubBlock.gif
throws HttpServerException ...{
InBlock.gif        String[] toks
= getRequest.split("/s");
ExpandedSubBlockStart.gifContractedSubBlock.gif
if (toks.length !=3) ...{
InBlock.gif
thrownew HttpServerException("Bad get request");
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif
if (!toks[0].toUpperCase().equals("GET")) ...{
InBlock.gif
thrownew HttpServerException("Bad get request");
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif
if (!toks[2].equals("HTTP/1.1")) ...{
InBlock.gif
thrownew HttpServerException("Not a HTTP/1.1 request");
ExpandedSubBlockEnd.gif        }

InBlock.gif
return toks[1];
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
publicstaticvoid main(String[] args) ...{
InBlock.gif        SimpleHttpGetServer server
=new SimpleHttpGetServer();
ExpandedSubBlockStart.gifContractedSubBlock.gif
try...{
InBlock.gif            server.start(DEFAULT_PORT);
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
catch (IOException e) ...{
InBlock.gif
// TODO Auto-generated catch block
InBlock.gif
           e.printStackTrace();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}