【问题标题】:Java String Index Out of Range in Proxy代理中的 Java 字符串索引超出范围
【发布时间】:2015-01-04 01:39:04
【问题描述】:

大家好,我的以下代码是用 java 编写的代理。 每次我尝试运行它时,它都会抛出一个字符串索引超出范围:-1 异常,我不知道如何处理。 如果 URL 或网页内容中写了“坏”字,我还需要将请求重定向到特定网页。 我怎么做? 请帮帮我!

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ProxyServer{
    //Create the Port the user wants the proxy to be on

    static Scanner sc = new Scanner(System.in);
    public static final int portNumber = sc.nextInt();

    public static void main(String[] args) {
        ProxyServer proxyServer = new ProxyServer();

        proxyServer.start();

    }

    public void start() {
        System.out.println("Starting the SimpleProxyServer ...");
        try {
            //bad list of words
            String bad[]= new String[4];
            bad[0]= "SpongeBob";
             bad[1]= "Britney Spears";
             bad[2]= "Norrköping";
             bad[3]= "Paris Hilton";


            ServerSocket serverSocket = new ServerSocket(ProxyServer.portNumber);// this is the socket of the proxy
            System.out.println(serverSocket);
            byte[] buffer= new byte [10000] ;
//
            while (true) {
                Socket clientSocket = serverSocket.accept();    // the client willl be the socket the proxy "accepts"
                boolean badContent =false;      //flag, if the input contains one of the bad words
                InputStream inputstream = clientSocket.getInputStream();    // retreiving request from the client


                int n = inputstream.read(buffer);       //reading buffer and storing its size

                String browserRequest= new String(buffer,0,n+1);  //new String(buffer,0,n);

                String realbrowserRequest =( browserRequest+"Connection close()");

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));

                for (int j=0; j<bad.length;j++){                        //checking of the URL contains the bad words
                    if(realbrowserRequest.contains(bad[j])){
                        badContent =true;                               // if yes the flag will be set to true
                    }
                }    

                //if(badContent == true){
                    //System.out.println("bad detected");

//                  try
//                  {
//                    URL url = new URL( "http://www.ida.liu.se/~TDTS04/labs/2011/ass2/error2.html" );
//
//                    BufferedReader in = new BufferedReader(
//                      new InputStreamReader( url.openStream() ) );
//
//                    String s;
//
//                    while ( ( s = in.readLine() ) != null )
//                      System.out.println( s );
//
//                    in.close();
//                  }
//                  catch ( MalformedURLException e ) {
//                      System.out.println( "MalformedURLException: " + e );
//                  }
//                  catch ( IOException e ) {
//                      System.out.println( "IOException: " + e );
//                  }





               // else{





                System.out.println("Das ist der Browserrequest: \n"+realbrowserRequest);
                System.out.println("Das ist der Erste Abschnitt");


                int start = browserRequest.indexOf(("Host: ") + 6);
                int end = browserRequest.indexOf('\n', start);
                String host = browserRequest.substring(start, end-1  );             //retreiving host

                if(badContent =true)                                                //if the URL already contains inappropriate material
                {
                    URL url = new URL( "http://www.ida.liu.se/~TDTS04/labs/2011/ass2/error2.html" );
                    host = url.getHost();                                           // set the host to the given one
                }
                System.out.println("Connecting to host " + host);

                Socket hostSocket = new Socket(host, 80); //I can change the host over here
                OutputStream HostOutputStream = hostSocket.getOutputStream();
//                PrintWriter writer= new PrintWriter (HostOutputStream);
//                writer.println();


                System.out.println("Forwarding request to server");
                HostOutputStream.write(buffer, 0, n);// but then the buffer that is fetched from the client remains same
                HostOutputStream.flush();


                InputStream HostInputstream = hostSocket.getInputStream();


                    OutputStream ClientGetOutput = clientSocket.getOutputStream();



                System.out.println("Forwarding request from server");

                do {
                    n = HostInputstream.read(buffer);

                    String vomHost = new String(buffer,0,n);
                    System.out.println("\nVom Host\n\n"+vomHost);

                    for(int i=0;i<bad.length;i++){
                        if(vomHost.contains(bad[i])){
                            badContent=true;    
                        }
                    }
                    System.out.println("Receiving " + n + " bytes");
                    if (n > 0) {                        // && badContent == false

                        ClientGetOutput.write(buffer, 0, n);
                    }
                } while (n>0  && badContent == false);                          //n>0&& badContent == false
                if (badContent == true){


                }
                ClientGetOutput.flush();
                hostSocket.close();
                clientSocket.close();
                System.out.println("End of communication");
                }


            }


         catch (IOException e) {
            e.printStackTrace();
        }


            }   
}

【问题讨论】:

  • 您在哪一行得到异常?发布堆栈跟踪
  • 您的代码有几个问题。例如,您的内容总是很糟糕:if(badContent =true)。请尝试更准确的错误描述。

标签: java string out


【解决方案1】:

你的代码有很多问题:

1) 换行:

int start = browserRequest.indexOf(("Host: ") + 6);

收件人:

int start = browserRequest.indexOf("Host:") + 6;

正如ToYonos的回答中提到的,因为它是错误的。

2) 你必须确保startend 这两个变量不等于-1(如果它们在browserRequest 中不存在):

if(end>start && start>0)
{
  String host = browserRequest.substring(start, end-1  ); 
}

这样可以避免很多异常。

【讨论】:

  • 谢谢我改变了我的大部分代码,它现在可以工作了。 (如果我在所有情况下都添加最后一个 if 语句;))
  • 现在我有过滤的问题,如果请求的 URL 或网页内容包含“坏”字词之一,我想要一个对新 URL 的 GET 请求。我该怎么做?
【解决方案2】:

问题就在这里:

int start = browserRequest.indexOf(("Host: ") + 6);

这意味着你正在这样做:

int start = browserRequest.indexOf("Host: 6");

6 被连接到"Host : "

试试这个:

int start = browserRequest.indexOf("Host: ") + 6;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2015-04-01
    • 2012-01-15
    • 2014-06-12
    • 2012-06-04
    • 1970-01-01
    相关资源
    最近更新 更多