我正在为课堂构建一个小 API,老师为我们提供了一个教程链接,该教程提供了一个实现 Runnable 的简单网络服务器。
我已经编写了一些代码来解析参数(或者至少让我得到请求字符串)和一些将返回一些简单 xml 的代码。
但是我认为发送了某些请求,例如针对 favicon 的请求,我认为它弄乱了我的代码。我将它包装在 if else 中,但它似乎不起作用。
=====已编辑因为基本字符串比较错误=====
package server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.*;
import java.io.*;
import java.net.*;
import parkinglots.*;
/**
import our API
*/
public class WorkerRunnable implements Runnable{
protected Socket clientSocket = null;
protected String serverText = null;
public WorkerRunnable(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
public Boolean authenticateAPI(String key){
//Authenticate Key against Stored Keys
//TODO: Create Stored Keys and Compare
return true;
}
public void run() {
try {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
//TODO: Parse args and output different formats and Authentication
//Parse URL Arguments
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream(), "8859_1"));
String request = in.readLine();
//Server gets Favicon Request so skip that and goto args
System.out.println(request);
if ( !"GET /favicon.ico HTTP/1.1".equals(request) && !"GET / HTTP/1.1".equals(request) && !"".equals(request) ){
String format = "", apikey ="";
System.out.println("I am Here");
String request_location = request.split(" ")[1];
String request_args = request_location.replace("/","");
request_args = request_args.replace("?","");
String[] queries = request_args.split("&");
System.out.println(queries[0]);
for ( int i = 0; i < queries.length; i++ ){
if( queries[i].equals("format") ){
format = queries[i].split("=")[1];
}
else if( queries[i].equals("apikey") ){
apikey = queries[i].split("=")[1];
}
}
if( apikey.equals("") ){
apikey = "None";
}
if( format.equals("") ){
format = "xml";
}
System.out.println("format: "+format);
Boolean auth = authenticateAPI(apikey);
if ( auth ){
if ( format.equals("xml")){
// Retrieve XML Document
String xml = LotFromDB.getParkingLotXML();
output.write((xml).getBytes());
}else{
//Retrieve JSON
String json = LotFromDB.getParkingLotJSON();
output.write((json).getBytes());
}
}else{
output.write(("Access Denied - User is Not Authenticated").getBytes());
}
}else{
output.write(("Access Denied Must Pass API Key").getBytes());
}
output.close();
input.close();
System.out.println("Request processed: " + time);
} catch (IOException e) {
//report exceptions
e.printStackTrace();
}
}
}
我得到的控制台输出
GET /?format=json HTTP/1.1
I am Here
format=json
json
format: xml
它也总是返回 XML。
这是我第一次接触到用 Java 编写 Web 服务器和处理网络,这让我很沮丧,所以这里的任何建议都非常感谢。
在得到其他人的一点帮助后,原来是这里的这一部分。我在比较字符串的错误部分,所以它永远不会匹配
if( queries[i].split("=")[0].equals("format") ){
format = queries[i].split("=")[1];
}
else if( queries[i].split("=")[0].equals("apikey") ){
apikey = queries[i].split("=")[1];
}