- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我正在尝试从 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/
我有一个可以从网站下载文件的 iOS 应用程序。我创建了一个 NSURLSession在一个类(class)Downloads来管理它们。 Downloads类有 NSMutableArray使用我的
您好,我正在尝试从 swift 客户端在 Java 服务器上执行简单的身份验证。 java 服务器是一个 HTTP 服务器,其代码接受带有用户名和密码的“POST”请求。如果用户名和密码正确,服务器返
我好像遇到了麻烦。出于某种原因,如果我尝试检查我的 NSURLSessionTask 对象的类类型,它根本不起作用。如果我检查它们的 taskDescription 属性,如果我在启动任务之前设置它们
我想知道是否可以重新运行失败的 NSURLSessionDataTask。这是我遇到此问题的背景。 我有一个 Web 服务对象,它使用 AFNetworking 2.0 来处理请求。在我的一种方法中,
这是 Apple 文档中关于 NSURLSessionTask 类的 suspend 方法的内容 A task, while suspended, produces no network traffi
我正在使用带有后台 session 的 NSURLSessionDownloadTask 来实现我所有的 REST 请求。这样我就可以使用相同的代码,而不必考虑我的应用程序是在后台还是在前台。 我的后
我想创建文件下载管理器来下载多个具有下载百分比和播放暂停删除功能的文件。 我尝试使用以下代码成功下载多个文件...但无法添加进度条请帮忙 for (int i = 0; i 然后您需要遵循以下代码:
假设我有一个正在运行的NSURLSessionUploadTask。如果应用程序在该时间范围内被终止或崩溃,待处理的请求会发生什么?任务仍然会完成还是也会终止? 最佳答案 这是凭内存而来的,所以对它持
我几乎可以肯定,我最近看到了一种与网络相关的方法,该方法允许使用 NSDictionary 设置 URL 参数。 它是新 NSURLSession 类的一部分,但我找不到它。 本质上,而不是像...那
我使用 NSURLSessionTask 并且我正在尝试监控我的一些 HTTP 请求需要多长时间,当 NSURLSessionTask 实际上发出初始请求?如果这是 NSOperation 中的 NS
这个问题在这里已经有了答案: block until reverseGeocode has returned (1 个回答) 关闭 7 年前。 我有一个简单的 NSURLConnection 任务
我正在使用 AFNetwork 3.0 进行 HTTP 获取请求。我什至得到回应。但我想将响应数据作为 NSString。有人可以帮我如何获取响应数据作为 NSString 这是我的代码, AFHTT
我经常有这样的代码,当我有一个处理与 REST API 通信的类时,里面有很多方法使用 NSURLSession 任务,闭包作为回调。我还提供了其中一些方法的回调闭包,这样我就可以一个接一个地链接不同
制作 NSURLSessionTasks 串行队列的最佳实践是什么? 就我而言,我需要: 获取 JSON 文件中的 URL(NSURLSessionDataTask) 在该 URL 下载文件 (NSU
在我的 iOS 应用程序中,我使用 NSURLSessionTask 将 json 数据下载到我的应用程序。我发现当我直接从浏览器调用 url 时,我会得到一个最新的 json,而当它从应用程序中调用
我的 Swift 应用程序有一个奇怪的行为,我目前不明白。 我对 NSOperation 进行了子类化,以创建可以通过 NSURLSession/NSURLSessionTask 调用 Rest-We
我为我的应用程序编写了一个单独的 WebServices 类 - WebServices.m。 其中,我有几个静态方法,例如 setUserInput()、getUserProfile()、regis
当我关闭 WiFi 连接并在 iPhone 6s 10.2 模拟器上运行以下代码时,回调永远不会执行。我预计回调会很快触发,并出现“无互联网连接”之类的错误。 NSLog(@"request-star
我正在实现自定义 NSURLProtocol,并且在内部希望使用 NSURLSession 处理内部网络的数据任务,而不是 NSURLConnection。 我遇到了一个有趣的问题,想知道 NSURL
如果我创建一个 NSURLSessionDownloadTask,然后在它完成之前取消它,完成 block 似乎仍然会触发。 let downloadTask = session.downloadTa
我是一名优秀的程序员,十分优秀!