我正在编写 HTTP WEB SERVER 代码。
直到现在我实施了 GET,HEAD 方法。现在我必须实现OPTIONS方法。但这次客户的shell没有收到任何回复。我不明白为什么会这样。请帮助我。我发布了我的代码,请帮助检测错误。
我的代码
客户端
public class Client {
public static void main(String[] args) {
HttpClient client = new HttpClient();
client.getParams().setParameter("http.useragent", "Test Client");
BufferedReader br = null;
OptionsMethod method = new OptionsMethod("http://10.40.55.240:8080/");
try {
int returnCode = client.executeMethod(method);
if(returnCode == 405 ) {
System.out.println("The Options method is not implemented by this URI");
} else {
System.out.println("REACH HERE");
br = new BufferedReader(new InputStreamReader(/*What I put here to get socket InputStream*/);
String readLine;
while((readLine = br.readLine()) != null) {
System.out.println(readLine);
}
}
//System.out.println(returnCode);
} catch(Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
if(br != null) {
try {
br.close();
}
catch(Exception e) {}
}
}
}
}
响应客户的服务器代码
else if(methodName.equals("OPTIONS")) {
System.out.println("GOING TO HANDLE OPTIONS REQUEST");
printStream.print("HTTP/1.1 " + ServerSettings.HTTP_OK + " OK");
printStream.write(EOL);
printStream.print("Date: " + new Date());
printStream.write(EOL);
printStream.print("Allow: OPTIONS, GET, HEAD");
printStream.write(EOL);
printStream.print("Content-Length: 0");
printStream.write(EOL);
}
inputStream.close();
printStream.close();
请帮帮我,如何从服务器接收标题。
我应该在客户端的注释部分放置什么来接收标题。
br = new BufferedReader(new InputStreamReader(/*What I put here to get socket InputStream*/);
答案 0 :(得分:0)
我得到了上述问题的答案,如下: -
由于Response Body
没有Options Method
。所以,这里服务器只响应Header,它可以在客户端shell上显示,使用以下语句: -
int returnCode = client.executeMethod(method);
if(returnCode == 405 ) {
System.out.println("The Options method is not implemented by this URI");
} else {
Header[] header = method.getResponseHeaders();
for(int i = 0; i < header.length; i++) {
System.out.println(header[i].getName() + ": " + header[i].getValue());
}
}
如果对于其他方法,如果还有任何响应体,那么我们可以使用下面的代码,
try {
int returnCode = client.executeMethod(method);
if(returnCode == 405 ) {
System.out.println("The XXX method is not implemented by this URI");
} else {
Header[] header = method.getResponseHeaders();
for(int i = 0; i < header.length; i++) {
System.out.println(header[i].getName() + ": " + header[i].getValue());
}
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
byte[] buf = new byte[1024];
String readLine;
while (((readLine = br.readLine()) != null)) {
System.out.println(readLine);
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
System.out.println("close method");
method.releaseConnection();
try {
br.close();
}
catch(IOException ioe) {}
}