gpt4 book ai didi

java - Java 中的 StringIndexOutOfBoundsException?

转载 作者:行者123 更新时间:2023-11-30 03:55:17 27 4
gpt4 key购买 nike

我尝试运行这个 java 程序,它会在我的 webroot 文件夹中返回一个网页

import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class WebServer {

static ServerSocket requestListener;
static Socket requestHandler;
static Scanner requestReader, pageReader;
static DataOutputStream pageWriter;
static String HTTPMessage;
static String requestedFile;
public static int HTTP_PORT = 12346;

public static void main(String[] args) {

try {

requestListener = new ServerSocket(HTTP_PORT);

System.out.println("Waiting For IE to request a page:");
requestHandler = requestListener.accept();
System.out.println("Page Requested: Request Header:");

requestReader = new Scanner(new InputStreamReader(
requestHandler.getInputStream()));
//THis is the part where its throwing the error

int lineCount = 0;
do {

lineCount++; // This will be used later
HTTPMessage = requestReader.next();
System.out.println(HTTPMessage);
if (lineCount == 1) {
requestedFile = "WebRoot\\"
+ HTTPMessage.substring(5,
HTTPMessage.indexOf("HTTP/1.1") - 1);
requestedFile = requestedFile.trim();
}

// localhost:12346/default.htm
// HTTPMessage = requestReader.nextLine();
pageReader = new Scanner(new File(requestedFile));
pageWriter = new DataOutputStream(
requestHandler.getOutputStream());
while (pageReader.hasNext()) {
String s = pageReader.nextLine();
// System.out.println(s);
pageWriter.writeBytes(s);
}
// Tells the Browser we’re done sending
pageReader.close();
pageWriter.close();
requestHandler.close();

} while (HTTPMessage.length() != 0);
} catch (Exception e) {

System.out.println(e.toString());
System.out.println("\n");
e.printStackTrace();
}
}
}

我收到此错误消息。我应该在 IE 中获取网页,但我却收到此错误消息。

等待 IE 请求页面:

Page Requested: Request Header:
GET
java.lang.StringIndexOutOfBoundsException: String index out of range: -7
at java.lang.String.substring(Unknown Source)
at WebServer.main(WebServer.java:39)

最佳答案

抛出此错误是因为字符串“HTTPMessage”不包含字符串“HTTP/1.1”。因此

HTTPMessage.indexOf("HTTP/1.1")  => returns -1

所以在你的子字符串函数中,这就是传递的内容:

 HTTPMessage.substring(5, -2);

因此出现错误。

要解决此错误,您应该首先尝试检查 HTTPMessage 是否包含所需的字符串,然后尝试计算子字符串。进行以下更改:

 if (lineCount == 1 && HTTPMessage.indexOf("HTTP/1.1") != -1) {
requestedFile = "WebRoot\\"
+ HTTPMessage.substring(5,
HTTPMessage.indexOf("HTTP/1.1") - 1);
requestedFile = requestedFile.trim();
}

关于java - Java 中的 StringIndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com