I use AFNetworking to post some JSON data to the server, and the server will response with the same JSON data.
Here is the objc code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager POST:@"http://127.0.0.1:5000/test" parameters:@{@"value":@(1)} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON:%@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];
The server code (use Flask):
@app.route('/test', methods = ['POST'])
def test():
resultJson = json.dumps(request.json)
response = make_response(resultJson)
return response
Wnen I run the code,it occurred an error:
Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x7febc2d33560 {com.alamofire.serialization.response.error.response= { URL: http://127.0.0.1:5000/test } { status code: 200, headers { "Content-Length" = 12; "Content-Type" = "text/html; charset=utf-8"; Date = "Mon, 02 Feb 2015 01:10:55 GMT"; Server = "Werkzeug/0.9.6 Python/2.7.6"; } }, NSErrorFailingURLKey=http://127.0.0.1:5000/test, com.alamofire.serialization.response.error.data=<7b227661 6c756522 3a20317d>, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
I cannot understand why the status code is 200 since there is an error, and why the error message shows that the Content-Type is text/html, I have set the Content-Type to application/json in my Objective-C code above.
However, things work well when I use VisualJSON(a Mac app).
You returned JSON data as a response, but your assumption that you set Content-Type is incorrect. Create a response instance with the mimetype set to 'application/json'.
from flask import request, json
@app.route('/test', methods=['POST'])
def test():
data = json.dumps(request.get_json())
resp = app.response_class(data, mimetype='application/json')
return resp