Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java代理服务器,it';It’有些页面不起作用。它适用于一些静态页面_Java_Http_Proxy Server - Fatal编程技术网

Java代理服务器,it';It’有些页面不起作用。它适用于一些静态页面

Java代理服务器,it';It’有些页面不起作用。它适用于一些静态页面,java,http,proxy-server,Java,Http,Proxy Server,我用java编写了一个代理服务器,但不知怎么的,它没有加载大部分页面。类似下面的链接:(也可以发布请求) ! 谁能给我一个提示。 这是我的代理服务器代码。 Server.java: DataStructure.java: Cache.java: 封装测试; 导入java.io.BufferedOutputStream; 导入java.io.BufferedReader; 导入java.io.BufferedWriter; 导入java.io.File; 导入java.io.FileInputSt

我用java编写了一个代理服务器,但不知怎么的,它没有加载大部分页面。类似下面的链接:(也可以发布请求)

!

谁能给我一个提示。 这是我的代理服务器代码。

Server.java:

DataStructure.java:

Cache.java:

封装测试;
导入java.io.BufferedOutputStream;
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.FileReader;
导入java.io.FileWriter;
导入java.io.IOException;
导入java.text.simpleDataFormat;
导入java.util.Date;
导入java.util.Iterator;
导入java.util.Locale;
导入java.util.Vector;
公共类缓存{
专用向量表;
简化格式df;
public Cache()抛出ClassNotFoundException,IOException
{
表=新向量();
df=新的简化格式(“MM/dd/yyyy HH:MM:ss”);
loadFromFile();
}
私有void saveToFile()引发IOException
{
试一试{
弦线;
File File=新文件(“cacheTable.ser”);
如果(!file.exists()){
createNewFile();
}
FileWriter fw=新的FileWriter(file.getAbsoluteFile());
BufferedWriter bw=新的BufferedWriter(fw);
int tableSize=table.size();
write(表大小+“\r\n”);

对于(int i=0;i什么确切的意思是“它不工作”?有任何异常吗?我得到这个错误:代理服务器拒绝连接
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);
        }
    }   
    }
}
}
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();
    }
}
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;
    }
}