我的服务器代码如:
// golang
type SomeHandler struct{}
func (*SomeHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
fmt.Println("method:", req.Method)
fmt.Println("content length:", req.ContentLength)
// read request body as []byte
content, err := ioutil.ReadAll(req.Body)
if err != nil {
// do sth.
return
}
// decode JSON
// ...
}
Run Code Online (Sandbox Code Playgroud)
客户端:
// Objective-C on iOS 6/7
// NSURL *myUrl = ...
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:myUrl];
[req setHTTPMethod:@"POST"];
[req setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
id obj = @{
@"username" : @"myname",
@"password" : @"mypwd",
};
NSError *error;
NSData *inputJson = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&error];
if (error) {
// no error here
}
[req setHTTPBody:inputJson];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"ERROR: %@", error.localizedDescription);
return;
}
NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
NSString *outputText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"response (%d):\n%@", (int)resp.statusCode, outputText);
}
Run Code Online (Sandbox Code Playgroud)
当我在iPhone模拟器中运行此iOS代码时,服务器端显示:
method: GET
content length: 0
Run Code Online (Sandbox Code Playgroud)
Chage我的客户端代码:[req setHTTPMethod:@"HEAD"];,服务器工作:
method: HEAD
content length: <some length>
Run Code Online (Sandbox Code Playgroud)
我不知道客户端上的POST代码有什么问题,或者我应该在服务器上做什么来检索我的客户端发送的[]字节数据.
顺便说一下,我去的版本:
$ go version
go version go1.2.1 darwin/amd64
Run Code Online (Sandbox Code Playgroud)
我解决了这个!这么奇怪的行为.我不知道为什么会这样.
我注册我的处理程序,如:
// addr := ...
r := mux.NewRouter()
r.Handle("/abc", new(SomeHandler))
http.Handle("/", r)
// here mux is github.com/gorilla/mux
// these lines of code do the same thing as wrote:
// http.handle("/abc", new(SomeHandler))
err := http.ListenAndServe(addr, nil)
// ...
Run Code Online (Sandbox Code Playgroud)
然后我的客户发送请求说
http://addr:9999//abc
Run Code Online (Sandbox Code Playgroud)
但正确的URL应该是
http://addr:9999/abc
Run Code Online (Sandbox Code Playgroud)
/调用-stringByAppendingString:方法时生成的冗余.
| 归档时间: |
|
| 查看次数: |
674 次 |
| 最近记录: |