Java网络编程实例---------------------------------复杂些的HTTP客户端
发送HTTP 1.0请求和保存返回数据,要求HTML和Image
package com.bq; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; /** * 一个使用HTTP1.1的客户端 * @author 白强 * @version 1.0 */ public class ModifiedClient { private Socket moditifiedClient; private String hostName; private BufferedReader response; private String responseMessage="\r\n"; private PrintWriter sender; /** * 构造方法 */ public ModifiedClient() { try { System.out.println("Input hostName:"); BufferedReader wt = new BufferedReader(new InputStreamReader( System.in)); hostName = wt.readLine(); InetAddress address = InetAddress.getByName(hostName); moditifiedClient = new Socket(address, 80); sender = new PrintWriter(moditifiedClient.getOutputStream()); response = new BufferedReader(new InputStreamReader( moditifiedClient.getInputStream())); Get(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new ModifiedClient(); } /** * 取得数据 * @throws Exception */ private void Get() throws Exception { try { // 从浏览器抄来的 String command = "GET " + "/" + " HTTP/1.1\r\n" + "Host:" + hostName + "\r\n" + "Connection:keep-alive" + "\r\n" + "Cache-Control:max-age=0" + "\r\n" + "Accept: */*" +"\r\n" + "Accept-Charset:GBK,utf-8;q=0.7,*;q=0.3" + "\r\n" + "Accept-Language:zh-CN,zh;q=0.8" + "\r\n" + "User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75" + "\r\n" + "Cookie:JSESSIONID=7F7043A91B93CA3389843BE025113D9A" + "\r\n\r\n"; sendMessage(command); String header = response.readLine(); System.out.println(header); if (header == null) { System.out.println("Exit!!!"); System.exit(1); } else { while (header.length() > 0) { System.out.println(header); header = response.readLine(); } } saveMessage(); } catch (IOException i) { i.printStackTrace(); } } /** * 保存接收到的HTML文件 * @throws Exception */ private void saveMessage() throws Exception { String str = ""; while ((str = response.readLine()) != null) { responseMessage += str + "\n"; } System.out.println(responseMessage); System.out.println("Input fileName:"); BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); String fileName = wt.readLine(); FileOutputStream fileoutputstream = new FileOutputStream(fileName); fileoutputstream.write(responseMessage.getBytes("GBK")); System.out.println("file saved"); } /** * 发送请求 * @param data * @throws IOException */ private void sendMessage(String data) throws IOException { sender.print(data); sender.flush(); } public void setHostName(String hostname) { this.hostName = hostname; } }