Привет, ребята, мой следующий код - прокси, написанный в java. Каждый раз, когда я пытаюсь запустить его, он выдает индекс строки из диапазона: исключение -1, которое я не знаю, как обращаться. Я также хочу перенаправить запрос на определенную веб-страницу, если «неправильное» слово было написано в URL-адресе или содержимом веб-страницы. Как это сделать? Пожалуйста, помогите мне!Java String Index Out of Range в прокси
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)'. Пожалуйста, постарайтесь уточнить сообщение об ошибке. – SBI