0

您好,我正在尝试从 swift 客户端对 Java 服务器执行简单的身份验证。java 服务器是一个 HTTPServer,它的代码接受一个带有用户名和密码的“POST”请求。如果用户名和密码正确,则服务器返回 true,如果不是通过 JSON 数据,则返回 false。

我认为问题在于 swift 客户端。它似乎没有运行任务的完成代码,因此我不相信它实际上能够连接到服务器,在 localhost 上运行。客户端代码和服务器代码如下所示。你能告诉我为什么完成代码不会运行吗?并可能给我一个关于如何解决它的答案?

斯威夫特客户端:

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 服务器:

    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);
        }
    }
}

谢谢你!

4

1 回答 1

1

似乎程序在服务器有机会响应之前就终止了。因为我猜它是一个独立的应用程序,所以没有任何东西可以让它同时运行,所以可能在一个 swift 应用程序本身内部它会继续运行并且没有问题。

于 2015-06-25T17:48:22.850 回答