gpt4 book ai didi

java - NSURLSessionTask 的完成处理程序未运行

转载 作者:行者123 更新时间:2023-11-30 10:14:27 25 4
gpt4 key购买 nike

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

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

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

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

谢谢!

最佳答案

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

关于java - NSURLSessionTask 的完成处理程序未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31016885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com