我用java写了一个代理服务器,不知何故它没有加载大部分页面。像下面的链接:(也是POST请求)
例子!
谁能给我一个提示。
这是我的代理服务器代码。
服务器.java:
package test;
import java.util.Date;
import java.util.Iterator;
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.io.DataOutputStream;
import java.lang.String;
import java.io.File;
import java.io.FileReader;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.nio.ByteBuffer;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.net.ServerSocket;
public class Server {
private static Cache cache;
public static void main(String[] args) throws Exception {
cache = new Cache();
InetSocketAddress randPort = new InetSocketAddress(0);
HttpServer server = HttpServer.create(randPort, 0);
System.out.println(server.getAddress().getPort());
server.createContext("/", new ServHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class ServHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
/* retrieve request information from client */
Headers reqHeaders = exchange.getRequestHeaders();
URL urlObj = new URL(exchange.getRequestURI().toString());
String reqMethod = exchange.getRequestMethod();
System.out.println(exchange.getRemoteAddress().getHostString() + ": " + reqMethod + " " + exchange.getRequestURI().toString());
/* establish connection with server */
URLConnection conn = urlObj.openConnection();
((HttpURLConnection)conn).setRequestMethod(reqMethod);
/* transmit POST data */
if (reqMethod.equals("POST")) {
/* fetch the request params from client */
InputStreamReader postParams = new InputStreamReader(exchange.getRequestBody(),"utf-8");
BufferedReader bufRead = new BufferedReader(postParams);
String valueOfParams = bufRead.readLine();
postParams.close();
/* configure the connection to receive a POST request */
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", "" + valueOfParams.length());
/* write the POST information to the server connection */
DataOutputStream params = new DataOutputStream(conn.getOutputStream());
params.writeBytes(valueOfParams);
params.close();
}
/* transmit response headers; required by HEAD, GET, and POST */
Headers servRespHeaders = exchange.getResponseHeaders();
int headerResp = ((HttpURLConnection)conn).getResponseCode();
exchange.sendResponseHeaders(headerResp, 0);
/* transmit GET data */
if (reqMethod.equals("GET")) {
String URI = exchange.getRequestURI().toString();
int index;
if((index = cache.IsInCache(URI)) == -1)
{
ByteArrayOutputStream cacheFile = new ByteArrayOutputStream();
System.out.println("Sending content from server.");
InputStream webServRespStream = conn.getInputStream();
OutputStream servRespStream = exchange.getResponseBody();
int numRead;
byte buffer[] = new byte[0x10000];
cacheFile.reset();
while ((numRead = webServRespStream.read(buffer)) != -1){
servRespStream.write(buffer, 0, numRead);
cacheFile.write(buffer, 0, numRead);
}
webServRespStream.close();
servRespStream.close();
cache.StoreToCache(URI, cacheFile.toByteArray());
}
else
{
System.out.println("Sending response from cache.");
byte buffer[] = new byte[0x10000];
buffer = cache.ReturnPage(index);
System.out.println(buffer.toString());
OutputStream servRespStream = exchange.getResponseBody();
servRespStream.write(buffer, 0, buffer.length);
}
}
}
}
}
数据结构.java:
package test;
import java.util.Date;
public class DataStructure {
public int index;
public String link;
public Date date;
public DataStructure()
{
index = -1;
link = "";
date = new Date();
}
}
缓存.java:
package test;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Vector;
public class Cache {
private Vector<DataStructure> table;
SimpleDateFormat df;
public Cache() throws ClassNotFoundException, IOException
{
table = new Vector<DataStructure>();
df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
loadFromFile();
}
private void saveToFile() throws IOException
{
try {
String line;
File file = new File("cacheTable.ser");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
int tableSize = table.size();
bw.write(tableSize + "\r\n");
for(int i=0; i<tableSize; i++) {
bw.write(table.get(i).index + "\r\n");
bw.write(table.get(i).link + "\r\n");
String tmpDate = df.format(table.get(i).date);
bw.write(tmpDate + "\r\n");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void loadFromFile() throws IOException, ClassNotFoundException
{
try {
File file = new File("cacheTable.ser");
if(!file.exists()) {
System.out.println("Cannot open the cache table.");
return;
}
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int tableSize = Integer.parseInt(br.readLine());
for(int i=0; i<tableSize; i++) {
DataStructure tmp = new DataStructure();
tmp.index = Integer.parseInt(br.readLine());
tmp.link = br.readLine();
String tmpDate = br.readLine();
tmp.date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).parse(tmpDate);
table.add(tmp);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
public int StoreToCache(String link, byte[] page) throws IOException
{
if(IsInCache(link) != -1)
return -1;
DataStructure tmp = new DataStructure();
tmp.link = link;
tmp.index = table.size() + 1;
tmp.date = new Date();
table.add(tmp);
WritePage(tmp.index, page);
saveToFile();
return tmp.index;
}
public int IsInCache(String link)
{
Iterator<DataStructure> i = table.iterator();
while(i.hasNext()) {
DataStructure tmp = i.next();
if(tmp.link.equals(link))
return tmp.index;
}
return -1;
}
public byte[] ReturnPage(int index) throws IOException
{
Iterator<DataStructure> i = table.iterator();
while(i.hasNext()) {
DataStructure tmp = i.next();
if(tmp.index == index)
{
return ReadPage(index);
}
}
return null;
}
private void WritePage(int index, byte[] data)
{
String fileName = Integer.toString(index);
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(new File(fileName));
fos.write(data);
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
private byte[] ReadPage(int index)
{
String fileName = Integer.toString(index);
byte[] data = null;
try {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
data = new byte[(int)file.length()];
fis.read(data);
fis.close();
return data;
}
catch (IOException e) {
e.printStackTrace();
}
finally {
return data;
}
}
}