[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;
/**
*
Title: SimpleHttpProxy
*
Description:
*
Copyright: Copyright (c) 2006
* @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;
try
{
socketServer = new ServerSocket(PORT);
while(true)
{
try
{
final Socket socket = socketServer.accept();
(new Thread(){
public void run(){
SimpleHttpProxy.service(socket);
}
}).start();
}
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)
{
}
}
}
}
private static void service(Socket socket)
{
Socket remote = null;
try
{
socket.setSoTimeout(2000);
socket.setKeepAlive(false);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
/**
* 读取协议头的第一行
* 格式: GET http://www.mytest.com HTTP/1.1
*/
byte[] buffer = readLine(inputStream);
if(buffer.length < 1)
{
return;
}
String header = new String(buffer, "UTF-8");
String[] action = header.split(" ");
if(action.length < 3)
{
return;
}
String address = action[1];
/**
* 目标地址是从http协议的第一行取
* 目标主机应该从协议的Host头里面取,如果Host取不到, 从地址里面取
* 此处为了简化逻辑只从地址里面取host, 因此如果路径不是绝对路径就忽略
*/
if(address.startsWith("http://") == false)
{
return;
}
System.out.print(header);
URL url = new URL(address);
String host = url.getHost();
int port = (url.getP