我正在使用CocoaHTTPServer
进行服务器连接。在我的html页面(Web客户端)中有一些JSON数据,但是当我得到响应时,我没有在头文件中获取JSON数据。
以下是我的代码:
HTML页面
endAPSession: function (success, fail) {
this.endApSessionIssued = true;
console.log('endAPSession.');
this.proxyAjax({
url: 'http://192.168.123.1/stw-cgi-rest/network/wifi/connect',
username: this.username,
password: this.password,
method: 'PUT',
data: JSON.stringify(data),
contentType: 'application/json'
})
.done( function ( data, textStatus, jqXHR ) {
device.endApSessionIssued = false;
console.log("endAPSession success:", arguments);
return success(jqXHR);
})
.fail( function ( jqXHR, textStatus, errorThrown ) {
device.endApSessionIssued = false;
console.log("endAPSession fail:", jqXHR);
return fail(jqXHR);
})
},
var data = {
SSID: network.name,
Password: password,
SecurityMode: network.security
};
我正在添加此标题:
-(void) addHeaders:(HTTPMessage *)response {
[response setHeaderField:@"Access-Control-Allow-Origin" value:@"*"];
[response setHeaderField:@"Access-Control-Allow-Headers" value:@"accept,x-forwarded-url, authorization, content-type,username,password, camera-data"];
[response setHeaderField:@"Access-Control-Allow-Methods" value:@"HEAD,GET,PUT,DELETE,OPTIONS,POST"];
[response setHeaderField:@"Access-Control-Max-Age" value:@"86400"];
[response setHeaderField:@"Access-Control-Expose-Headers" value:@"content-type, content-length, connection, date, server, x-www-authenticate"];
}
我低于响应:
Accept = "*/*";
"Accept-Encoding" = "gzip, deflate";
"Accept-Language" = "en-us";
Authorization = "Digest username=\"admin\",realm=\"iPolis\",nonce=\"2f65566a6c6239a1358732f8bfe08909\",uri=\"/stw-cgi-rest/network/wifi/connect\",qop=auth,nc=00000001,cnonce=\"7007d989\",response=\"dae876901c002f20b3baa100580a1634\"";
Connection = "keep-alive";
"Content-Length" = 63;
"Content-Type" = "application/json";
Host = "127.0.0.1:8090";
Origin = "http://localhost:8090";
Referer = "http://localhost:8090/";
"User-Agent" = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13F69";
password = "";
username = admin;
"x-forwarded-url" = "http://192.168.123.1/stw-cgi-rest/network/wifi/connect";
这里我没有收到JSON响应。这里Content-Length
即将来临63.这意味着数据存在。但它不会来。
JSON应该是这样的:
"camera-data" = "{\"SSID\":\"HomeNetwork\",\"Password\":\"1234567\",\"SecurityMode\":\"PSK\"}";
如果我在我的html页面中添加以下代码,我的回复中会出现上述JSON,但我不想更改我的HTML页面。
if(proxyOpts.data != null) {
proxyOpts.headers['camera-data'] = proxyOpts.data;
}
那么请指导我如何在响应头中获取JSON?如何在我的回复中获得camera-data
。
答案 0 :(得分:1)
总而言之,为了确保我能正确理解这一点,您的网络客户端包含一些HTML& JavaScript代码。使用此JavaScript代码,您将向使用CocoaHTTPServer
托管的网络服务器发送请求。在此请求中,您将使用data: JSON.stringify(data)
发送JSON数据。您希望在服务器端获取和使用此数据。这是对的吗?
如果这是正确的,在服务器端,HTTPConnection
内的所有传入连接都会有CocoaHTTPServer
的自定义子类:
[httpServer setConnectionClass:[YourConnectionClass class]];
然后,您将在此子类中拥有(NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
的自定义实现。将调用此方法以获取每个请求的响应。在此方法中,您将能够检查请求的方法是否为您在JavaScript代码中指定的PUT
,以获取包含您的数据的请求正文等。
- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path {
// Check if the method is PUT.
if ([method isEqual:@"PUT"]) {
// Get the data sent in this request.
NSData *requestData = [request body];
// Transform the data into usable JSON.
NSError *error;
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:requestData options:kNilOptions error:&error];
// At this point, you have your json data send in the request, you can do anything with it.
// ...
// ...
}
// ...
// Return a proper response depending on the request.
// ...
}
您还需要确保允许使用不同的方法,PUT
显然和OPTIONS
以避免CORS问题。
- (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
{
if ([method isEqualToString:@"PUT"])
return YES;
if ([method isEqualToString:@"OPTIONS"])
return YES;
return [super supportsMethod:method atPath:path];
}
由于PUT方法发送数据,我们还需要使用processBodyData
方法在服务器端处理这些数据,该方法默认为空并且需要被覆盖。
- (void)processBodyData:(NSData *)postDataChunk
{
[request appendData:postDataChunk];
}
在我的HTTPConnection
子类中使用这三种方法,我可以使用与问题中的类似的JavaScript代码:
var data = { name: "HiDeo", location: "Internet", other: "test" };
$( document ).ready(function() {
$.ajax({
method: "PUT",
url: "http://localhost:12345/",
data: data,
username: "testUsername",
password: "testPassword",
data: JSON.stringify(data),
contentType: 'application/json'
})
.done(function( msg ) {
console.log(msg)
});
});
如果我在服务器端NSLog(jsonData);
,我将得到以下输出:
{
location = Internet;
name = HiDeo;
other = test;
}