我写了一个简单的代码,它是一个微型网络服务器。我想在客户端输入 loalhost:8181/pic
时显示图片但是当我 String str = in.readLine()
str show only localhost:8181 我怎么能找到在客户端的浏览器中输入 localhost:8181/pic
?这是我的简单代码:
protected void start() {
ServerSocket s;
System.out.println("Webserver starting up on port 80");
System.out.println("(press ctrl-c to exit)");
try {
// create the main server socket
s = new ServerSocket(8181);
} catch (Exception e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Waiting for connection");
for (;;) {
try {
Socket remote = s.accept();
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(
remote.getInputStream()));
PrintWriter out = new PrintWriter(remote.getOutputStream());
String method = in.readLine();
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
最佳答案
你需要更多这样的东西:
protected void start() {
ServerSocket s;
System.out.println("Webserver starting up on port 8181");
System.out.println("(press ctrl-c to exit)");
try {
// create the main server socket
s = new ServerSocket(8181);
} catch (Exception e) {
System.out.println("Error: " + e);
return;
}
for (;;) {
System.out.println("Waiting for connection");
try {
Socket remote = s.accept();
System.out.println("Connection established.");
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
PrintWriter out = new PrintWriter(remote.getOutputStream());
String tokens[] = in.readLine().split("\\s+") ;
if (tokens.length != 3)
{
out.println("HTTP/1.0 400 Bad Request");
out.println("Connection: close");
out.println("");
out.flush();
remote.close();
continue;
}
if ((tokens[2].compareToIgnoreCase("HTTP/1.0") != 0) &&
(tokens[2].compareToIgnoreCase("HTTP/1.1") != 0))
{
out.println("HTTP/1.0 505 HTTP Version Not Supported");
out.println("Connection: close");
out.println("");
out.flush();
remote.close();
continue;
}
if (tokens[0].compareToIgnoreCase("GET") != 0)
{
out.println("HTTP/1.0 405 Method Not Allowed");
out.println("Connection: close");
out.println("");
out.flush();
remote.close();
continue;
}
String path = tokens[1];
String query = null;
int idx = path.indexOf('?');
if (idx != -1)
{
query = path.substring(idx+1);
file = path.substring(0, idx);
}
if (path != "/pic")
{
out.println("HTTP/1.0 404 Not Found");
out.println("Connection: close");
out.println("");
out.flush();
remote.close();
continue;
}
out.println("HTTP/1.0 200 OK");
out.println("Connection: close");
out.println("Content-Type: ..."); // for you to fill in
out.println("Content-Length: ..."); // for you to fill in
out.println();
// write out image data here...
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
关于java - 使用网络类获取 url 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25316550/