我在这里设置了一个小型聊天室服务。主要重点是客户端和服务器类的get和post方法。我可以从客户端发送发帖请求,并从服务器上收到Created room <name created>
的回复。我不知道为什么我不能执行get请求,因为看起来它们几乎一样。我在访问http://localhost:8080/RestServer/serv/serverinrest
状态时收到的错误
修补some other solutions hasn't helped much,但也许我做错了
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Servlet.init() for servlet [Jersey Web Application] threw exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet.init() for servlet [Jersey Web Application] threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
...
...
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:834)
Root Cause
java.lang.IllegalArgumentException: java.text.ParseException: End of header
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:289)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:274)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.addProduces(IntrospectionModeller.java:173)
...
...
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.ja
Server.java
package serverPackage;
import java.io.IOException;
import java.util.LinkedList;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.web.bind.annotation.RequestHeader;
@Path("/serverinrest")
public class ServerInRest {
protected LinkedList<MyChatroom> chatRooms = new LinkedList<MyChatroom>(); //All the chatrooms on this Server. This chatrooms list and the userlist and messagelist in the chatrooms are the only stateful part of this server.
/*
* Constructor for the server. Initializes the Chatroom list and JSON parser
*/
public ServerInRest() {
chatRooms = new LinkedList<MyChatroom>();
}
/* Receives a message that is stored in the chatrooms messages list, and sends this message to all users in that chatroom.
* @Param user The user who is sending the message
* @Param room The room the message is to be sent to
* @Param message The message to be sent
*/
@Path("/message")
@PUT
@Produces("Application/Json")
public JSONObject message(@RequestHeader("user") String user, @RequestHeader("room") String room, @RequestHeader("message") String message) throws IOException {
String header = "Message";
String response = "Sent";
MyChatroom c = this.roomObject(room);
c.addMessage(message, user);
return conToJson(header,response);
}
/* Removes a user named in the user list of the chatroom
* @Param user The user to be removed
* @Param room The room the user will be removed from
*/
@Path("/leave")
@PUT
@Produces("application/xml")
public JSONObject leaveRoom(@RequestHeader("user") String user, @RequestHeader("room") String room) throws IOException {
String header = "Left Room";
String response = room;
MyChatroom c = this.roomObject(room);
c.removeUser(user);
return conToJson(header, response);
}
/* Adds a user to the user list of the chatroom
* @Param user The user to be added
* @Param room The room the user will be added to
*/
@Path("/join")
@PUT
@Produces("application/")
public JSONObject joinRoom(@RequestHeader("user") String user, @RequestHeader("room") String room){
String header = "Joined Room";
String response = room;
MyChatroom c = this.roomObject(room);
c.addUser(user);
return conToJson(header, response);
}
/* Creates a room for this server and adds it to the servers room list
* @Param room The name of the room
*/
@Path("{r}")
@POST
@Produces("application/json")
public JSONObject createRooms(@RequestHeader("room") String room){
String header = "Created_room";
String response = room;
MyChatroom c = new MyChatroom(room);
chatRooms.add(c);
return conToJson(header, response);
}
/* Lists the names of all the rooms on this server
* @return A string containing the names of all the rooms
*/
@GET
@Produces("application/json")
public JSONObject listRooms() {
print("test1");
String header = "Available_Rooms"; //% is used to determine if there needs to be user input or not
String rooms = "a";
for (int j = 0; j < chatRooms.size(); j++) {
// print("test2");
rooms = rooms + chatRooms.get(j).getName() + "\n";
}
print("test3");
//return "<ctofservice>" + "<celsius>" + "</celsius>" + "<ctofoutput>" + "</ctofoutput>" + "</ctofservice>";
return conToJson(header, rooms);
//return Response.status(200).entity(result).build();
}
/* Takes a room name and returns the room object with that name
* @param room: A string containing the name of the chatroom
* @return A chatroom containing the same name as name
*/
private MyChatroom roomObject(String room) {
for (int i = 0; i < chatRooms.size(); i++) {
MyChatroom c = chatRooms.get(i);
if (c.getName().equals(room)) {
return c;
}
}
return null;
}
private void print(String x) {
System.out.println(x);
}
/* Returns a JSONObject representation of a string
* @Param response: A string
* @Return A JSON representation of response
*/
private JSONObject conToJson(String header, String response) {
JSONObject j;
try {
j = new JSONObject();
j.put(header,response);
} catch (Exception e) {
System.out.println("test0");
return null;
}
return j;
}
}
Client.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.HttpClientBuilder;
//import org.apache.myfaces.push.util.Json;
//import org.apache.tomcat.util.json.JSONParser;
//import org.json.JSONObject;
/**
* @author Crunchify.com
*
*/
public class MyClient {
private String name;
private String sUrl = "http://localhost:8080/RestServer/serv/serverinrest/";
private Scanner reader;
public MyClient(String name) {
this.name = name;
this.reader = new Scanner(System.in);
this.run();
}
private String sResponse(HttpResponse response){
try {
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
// Get-Capture Complete application/xml body response
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
String rvalue = "";
// Simply iterate through XML response and show on console.
while ((output = br.readLine()) != null) {
rvalue = rvalue + output;
}
return rvalue;
}catch (Exception e) {
return "Couldn't break the value apart";
}
}
private String help() {
String message = "Create a chatroom: create \nList Chat Rooms: list \nJoin Chat Room: join \nLeave Chat Room: leave\n";
return message;
}
/*
* A post request to create a chatroom on the server
*/
private String create() {
print("Name the Chatroom");
//Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
//reader.close();
this.post(sUrl, input);
return "Created room " + input;
}
private String joinr() {
//String[] rooms = this.list().split(":");
//if (rooms[1].isBlank()) {
// return "There's no rooms to join";
//}else {
print("Which room would you like to join?");
// Scanner reader = new Scanner(System.in);
String room = reader.nextLine();
// reader.close();
return this.put(sUrl + "join", room, this.name, "");
//}
}
private String leave() {
print("Which room would you like to leave");
//Scanner reader = new Scanner(System.in);
String room = reader.nextLine();
//reader.close();
return this.put(sUrl + "leave", room, this.name, "");
}
private String increaseTime() {
print("Increase the time for which room?");
//Scanner reader = new Scanner(System.in);
String room = reader.nextLine();
//reader.close();
return this.put(sUrl + "increase", room, this.name, "");
}
/*
* Get request that receives the current timestamp of a room
*/
private String roomTime() {
print("Which room do you want the time for?");
//Scanner reader = new Scanner(System.in);
String room = reader.nextLine();
//reader.close();
return this.get(sUrl + "{" + room + "}");
}
/*
* Sends a get request that is responded to with a string than contains all the rooms
*/
private String list() {
return this.get( sUrl );
}
private void write(String msg) {
print("Which room would you like to Write to?");
//Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
//reader.close();
this.put(sUrl + "message", input, this.name, msg);
}
private String post(String url, String rName) {
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(url);
postRequest.addHeader("accept", "application/json");
postRequest.addHeader("room", rName);
// get requests accepts application/json data
HttpResponse response = httpClient.execute(postRequest);
// Check for HTTP response code: 200 = success
return sResponse(response);
} catch (ClientProtocolException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
}
return null;
}
private String put(String url, String room, String user, String message){
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPut putRequest = new HttpPut(url);
putRequest.addHeader("accept", "application/json"); // get requests accepts application/json data
putRequest.addHeader("room", room);
putRequest.addHeader("user", user);
putRequest.addHeader("message", message);
HttpResponse response = httpClient.execute(putRequest);
// Check for HTTP response code: 200 = success
return sResponse(response);
} catch (ClientProtocolException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();}
return null;
}
private String get(String url) {
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("accept", "application/json"); // get requests accepts application/json data
getRequest.addHeader("user", this.name);
HttpResponse response = httpClient.execute(getRequest);
// Check for HTTP response code: 200 = success
return response.toString();
} catch (ClientProtocolException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
}
return null;
}
public void run() {
// try {
//Scanner reader;
String input;//Check if there is input from the user
String output;
do {
System.out.println(this.help());
//reader = new Scanner(System.in);
input = reader.nextLine();
//if the user has disconnected from the server, remove them from the list
if (input.equals("create")){ //create a chat room
output = this.create();
print(output);
}else if (input.equals("list")) { //List the current chatrooms
output = this.list();
print(output);
}else if (input.equals("join")) { //Join the user to a chat room
output = this.joinr();
print(output);
}else if (input.equals("leave")) { //Remove the user from a chatroom
output = this.leave();
print(output);
}else if (input.equals("roomTime")) {
output = this.roomTime();
print(output);
}else if (input.equals("time")) {
long time = System.currentTimeMillis() / 1000;
output = String.valueOf(this.createDate(time));
print(output);
}else if (input.equals("increaseTime")) {
this.increaseTime();
}else if (input.equals("help")) {
print(this.help());
}else { //All other input is interpreted as a message to be posted in the chatrooms that the user is in
this.write(input);
}
} while (input != null);
//reader.close();
}
public String createDate(long time) {
Date date = new java.util.Date(time * 1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
return formattedDate;
}
static void print(String x) {
System.out.println(x);
}
public static void main(String args[]) {
print("Enter a name for yourself");
Scanner reader = new Scanner(System.in);
String name = reader.nextLine();
//reader.close();
MyClient client = new MyClient(name);
}
}
**Chatroom.java(Not necessary to look at, only here if you need it)**
package serverPackage;
import java.util.LinkedList;
//Each chatroom represents a space on the server that clients/users can interact with each other
public class MyChatroom {
private String name; //Name of the chatroom
protected LinkedList<String> messages; //List of text messages that have been sent by users to the chatroom and are displayed in the chatroom
protected long dateLastUsed; //The last time the chatroom was joined or had a message sent to it
protected LinkedList<String> users; //The clients/users that are currently in the chatroom, this list exists so that it is known who to message when a message is received
/*
* Chatroom constructor
* @param name The name of the chatroom, as determined by the user creating it
*/
public MyChatroom(String name) {
dateLastUsed = System.currentTimeMillis() / 1000; //Sent the time that the chatroom was used last to the current UNIX Epoch time
messages = new LinkedList<String>();
users = new LinkedList<String>();
this.name = name;
}
/*
* Adds a message into the chatroom
* @param message The message to be added to the chatroom
*/
protected void addMessage(String message, String user) {
messages.add(message);
String outMessage = "%Chatroom: " + getName() + " User: " + user + "\n" + message;
for (int n = 0; n < users.size(); n++) {
//this.users.get(n).write(outMessage.getBytes());
}
dateLastUsed = System.currentTimeMillis() / 1000;
}
/*
* Names a user in the user list of the chatroom
*/
protected void addUser(String user) {
users.add(user);
}
/*
* Removes a user named in the user list of the chatroom
*/
protected void removeUser(String user) {
users.remove(user);
}
/*
* Set's the time of the room so that the room looks like it's almost a week old
*/
protected void increaseTime() {
dateLastUsed = dateLastUsed - 604790;
}
/*
* Returns the name of the chatroom
* @return String equal to the name of the chatroom
*/
protected String getName() {
return this.name;
}
/*
* Returns the name of the chatroom in Unix Epoch Time
* @return Long equal to the time of the chatroom
*/
protected long getTime() {
return this.dateLastUsed;
}
}