java http代理
初學(xué)java就寫了個(gè)http代理練練手甘萧,把以前C語言寫的移植了下扬卷,不得不說Java寫起來是要比C語言簡(jiǎn)單的多怪得。
- LocalServer類 創(chuàng)建本地監(jiān)聽 接收客戶端請(qǐng)求
package cn.lbxx;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class LocalServer{
private static int LPort ; // 監(jiān)聽端口
private ServerSocket loSocket; // 本地套接字
public LocalServer() throws IOException {
loSocket = new ServerSocket(LPort);
}
public void start()
{
try {
System.out.println("run on " + LPort);
while(true)
{
Socket ct = loSocket.accept();
new HandleRequest(ct).start(); // 新建線程處理客戶端請(qǐng)求
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
LPort = 8853;
try {
new LocalServer().start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- HandleRequest類 處理客戶端請(qǐng)求
package cn.lbxx;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class HandleRequest extends Thread {
private static String KHost = "Host:";
private Socket clSocket ;
private Socket seSocket ;
private Scanner cdata ;
private String remotehost ;
private int remoteport ;
private boolean https ;
private List<String> bufflist ;
public HandleRequest(Socket c){
this.clSocket = c;
this.bufflist = new ArrayList<String>();
}
public void run()
{
try {
cdata = new Scanner(clSocket.getInputStream());
int beginIndex = KHost.length() + 1;
String line;
// 讀取客戶端的請(qǐng)求頭
while(cdata.hasNextLine() && (line = cdata.nextLine()).length() != 0)
{
if(line.length() > 5)
{
if(line.substring(0, KHost.length()).equals(KHost))
{
int hend;
if((hend = line.indexOf(':', beginIndex)) != -1)
{
remotehost = line.substring(beginIndex, hend);
remoteport = Integer.parseInt(line.substring(hend + 1));
} else {
remotehost = line.substring(beginIndex);
remoteport = 80;
}
}
// 判斷是否為https請(qǐng)求
if(line.substring(0, line.indexOf(' ')).equals("CONNECT")){
https = true;
}
if(line.matches("Proxy-Connection(.*)")){
line = "Connection: keep-alive";
}
}
bufflist.add(line);
}
if(remotehost != null)
{
System.out.println(remotehost + " -> " + remoteport + " " + https);
seSocket = new Socket(remotehost, remoteport); // 連接到遠(yuǎn)程主機(jī)
if (https) { // 客戶端與遠(yuǎn)程主機(jī)間數(shù)據(jù)轉(zhuǎn)發(fā)
List<String> list = new ArrayList<>();
list.add("HTTP/1.1 200 Connection Established");
new ForwardData(list, seSocket, clSocket).start();
new ForwardData(null, clSocket, seSocket).start();
} else {
toUri(bufflist);
new ForwardData(bufflist, clSocket, seSocket).start();
new ForwardData(null, seSocket, clSocket).start();
}
}
} catch (ConnectException c) {
System.err.println("鏈接超時(shí)");
} catch (SocketException se) {
System.err.println("無法連接-> " + remotehost + ":" + remoteport);
} catch (Exception e) {
System.err.println("發(fā)生錯(cuò)誤" + e);
}
}
// 將header轉(zhuǎn)換為path形式
private void toUri(List<String> buff)
{
for (int i = 0; i < buff.size(); i++)
{
String line = buff.get(i);
String head = line.substring(0, line.indexOf(' '));
int hlen = head.length() + 1;
if(line.substring(hlen, hlen + 7).equals("http://"))
{
String uri = line.substring(line.indexOf('/', hlen + 7));
buff.set(i, head + " " + uri);
break;
}
}
}
}
- ForwardData類 數(shù)據(jù)轉(zhuǎn)發(fā)
package cn.lbxx
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
public class ForwardData extends Thread {
private List<String> buff ;
private Socket source ;
private Socket destination ;
public ForwardData(List<String> buff, Socket sou, Socket des) {
this.buff = buff;
this.source = sou ;
this.destination = des ;
}
@Override
public void run() {
try {
OutputStream outStream = destination.getOutputStream();
InputStream inStream = source.getInputStream();
if(buff != null && buff.size() > 0){
for(String str : buff)
{
outStream.write((str + "\r\n").getBytes());
outStream.flush();
}
outStream.write("\r\n".getBytes());
outStream.flush();
}
byte[] bs = new byte[4096];
int len;
while ((len = inStream.read(bs)) != -1) {
outStream.write(bs, 0, len);
outStream.flush();
}
outStream.close();
inStream.close();
} catch (IOException ie) {
System.err.println("http 數(shù)據(jù)轉(zhuǎn)發(fā)異常 " + ie);
}
}
}
- 測(cè)試
smallproxy.png
很簡(jiǎn)單的代理例子蚕断,問題有不少經(jīng)過測(cè)試多數(shù)網(wǎng)站都能代理,性能速度方面就沒去測(cè)試因谎,多線程應(yīng)該還不錯(cuò)吧基括,有空繼續(xù)優(yōu)化吧。