您好我正在尝试从swift客户端在Java服务器上执行简单身份验证。 java服务器是一个HTTPServer,它的代码采用" POST"请求使用用户名和密码。如果用户名和密码正确,则服务器返回true;如果不是通过JSON数据,则返回false。
我相信的问题在于快速的客户。它似乎没有运行任务的完成代码,因此我不相信它实际上能够连接到服务器,在localhost上运行。客户端代码和服务器代码如下所示。你能否告诉我为什么完成代码不会运行?并可能给我一个如何解决它的答案?
Swift客户端:
import Foundation
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration)
let usr = "TBecker"
let pwdCode = "TBecker"
let params:[String: AnyObject] = [
"User" : usr,
"Pass" : pwdCode ]
let url = NSURL(string:"http://localhost:8080/auth")
let request = NSMutableURLRequest(URL: url)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
if (NSJSONSerialization.isValidJSONObject(params)) {
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
} catch {
print("catch failed")
}
}
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
print("response was not 200: \(response)")
return
}
}
if (error != nil) {
print("error submitting request: \(error)")
return
}
// handle the data of the successful response here
if (NSJSONSerialization.isValidJSONObject(data!)) {
do {
print("received data of some sort")
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
print(result)
} catch {
print("catch failed")
}
}
})
task.resume()
Java Server:
public class HTTPRequestHandler {
private static final String HOSTNAME = "localhost";
private static final int PORT = 8080;
private static final int BACKLOG = 1;
private static final String HEADER_ALLOW = "Allow";
private static final String HEADER_CONTENT_TYPE = "Content-Type";
private static final Charset CHARSET = StandardCharsets.UTF_8;
private static final int STATUS_OK = 200;
private static final int STATUS_METHOD_NOT_ALLOWED = 405;
private static final int NO_RESPONSE_LENGTH = -1;
private static final String METHOD_POST = "POST";
private static final String METHOD_OPTIONS = "OPTIONS";
private static final String ALLOWED_METHODS = METHOD_POST + "," + METHOD_OPTIONS;
public static void main(final String... args) throws IOException {
final HttpServer server = HttpServer.create(new InetSocketAddress(HOSTNAME, PORT), BACKLOG);
server.createContext("/auth", he -> {
try {
System.out.println("Request currently being handled");
final Headers headers = he.getResponseHeaders();
final String requestMethod = he.getRequestMethod().toUpperCase();
switch (requestMethod) {
case METHOD_POST:
final Map<String, List<String>> requestParameters = getRequestParameters(he.getRequestURI());
// do something with the request parameters
final String success;
if (requestParameters.containsKey("User") && requestParameters.containsKey("Pass"))
if (requestParameters.get("User").equals("TBecker") && requestParameters.get("Pass").equals("TBecker")) {
success = "['true']";
} else {
success = "['false']";
}
else
success = "['false']";
headers.set(HEADER_CONTENT_TYPE, String.format("application/json; charset=%s", CHARSET));
final byte[] rawSuccess = success.getBytes(CHARSET);
he.sendResponseHeaders(STATUS_OK, rawSuccess.length);
he.getResponseBody().write(rawSuccess);
break;
default:
headers.set(HEADER_ALLOW, ALLOWED_METHODS);
he.sendResponseHeaders(STATUS_METHOD_NOT_ALLOWED, NO_RESPONSE_LENGTH);
break;
}
} finally {
System.out.println("request successfully handled");
he.close();
}
});
server.start();
}
private static Map<String, List<String>> getRequestParameters(final URI requestUri) {
final Map<String, List<String>> requestParameters = new LinkedHashMap<>();
final String requestQuery = requestUri.getRawQuery();
if (requestQuery != null) {
final String[] rawRequestParameters = requestQuery.split("[&;]", -1);
for (final String rawRequestParameter : rawRequestParameters) {
final String[] requestParameter = rawRequestParameter.split("=", 2);
final String requestParameterName = decodeUrlComponent(requestParameter[0]);
requestParameters.putIfAbsent(requestParameterName, new ArrayList<>());
final String requestParameterValue = requestParameter.length > 1 ? decodeUrlComponent(requestParameter[1]) : null;
requestParameters.get(requestParameterName).add(requestParameterValue);
}
}
return requestParameters;
}
private static String decodeUrlComponent(final String urlComponent) {
try {
return URLDecoder.decode(urlComponent, CHARSET.name());
} catch (final UnsupportedEncodingException ex) {
throw new InternalError(ex);
}
}
}
谢谢你!
答案 0 :(得分:1)
似乎程序在服务器有机会响应之前终止。由于我猜它是一个独立的应用程序,没有任何东西可以让它同时运行,所以可能在一个快速的应用程序本身内它会继续运行而没有问题。