http代理工作原理(3)
代码如下:[java]
/**
* 某些服务器对协议头必须一次性读完, 例如QQ空间
* 因此此处先读出协议头, 并且一次写入, 写入之后必须flush
* 否则就跳转到QQ首页了
*/
long contentLength = -1L;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(buffer, 0, buffer.length);
/**
* 读取协议头
* 也可以不读取协议头, 而是直接把inputStream写入到remoteOutputStream
* 为了兼容某些服务器, 此处简单的读取一下协议头
*/
while((buffer = readLine(inputStream)).length > 0)
{
header = new String(buffer, "UTF-8").trim();
if(header.length() < 1)
{
break;
}
if(header.startsWith("Content-Length:"))
{
try
{
contentLength = Long.parseLong(header.substring(15).trim());
}
catch(NumberFormatException e){}
}
bos.write(buffer, 0, buffer.length);
}
/** 协议头和主体之间的空行 */
bos.write(CRLF);
remoteOutputStream.write(bos.toByteArray());
remoteOutputStream.flush();
/** 如果存在contentLength */
if(contentLength > 0)
{
copy(inputStream, remoteOutputStream, 4096, contentLength);
}
其他的代码就跟之前的一样了, 完整的代码如下:
[java]
/*
* $RCSfile: SimpleHttpProxy.java,v $$
* $Revision: 1.1 $
* $Date: 2013-1-9 $
*
* Copyright (C) 2008 Skin, Inc. All rights reserved.
*
* This software is the proprietary information of Skin, Inc.
* Use is subject to license terms.
*/
package test.com.skin.http.proxy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* <p>Title: SimpleHttpProxy</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* @author xuesong.net
* @version 1.0
*/
public class SimpleHttpProxy
{
public static final int PORT = 6666;
public static final byte[] CRLF = new byte[]{0x0D, 0x0A};
/**
* @param args
*/
public static void main(String[] args)
{
ServerSocket socketServer = null;
BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(1024);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(512, 1024, 30000, TimeUnit.SECONDS, blockingQueue);
try
{
socketServer = new ServerSocket(PORT);
while(true)
{
try
{
final Socket socket = socketServer.accept();
Runnable job = new Runnable(){
public void run(){
SimpleHttpProxy.service(socket);
}
};
threadPoolExecutor.execute(job);
}
catch(SocketTimeoutException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(socketServer != null)
{
try
{
socketServer.close();
}
catch(IOException e)
{
<补充:软件开发 , Java ,