我正在尝试以下面的形式生成json并将其发布到服务器:
{
"items": [
{
"id": "3",
"quantity": 0.5,
"unit": "2"
} ]
}
我使用ASIFormDataRequest
发布数据。我已经转义了json字符串,以便将其作为请求参数发送到url
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://api.esha.com/analysis?items=%@&apikey=%@",encodeJson,ApiKey]];
//here i have send escaped json (do I really need to do this thing?)
_request = [ASIFormDataRequest requestWithURL:url];
[_request setPostValue:jsonString forKey:@"items"]; //original json string
[_request setPostValue:ApiKey forKey:@"apikey"];
[_request setRequestMethod:@"POST"];
[_request addRequestHeader:@"Content-Type" value:@"application/json"];
[_request setDelegate:self];
_request.timeOutSeconds = 60.0;
[_request startSynchronous];
作为回应,我收到HTML格式的“不支持的媒体类型”错误:
<body>
<h1>HTTP Status 415 - Unsupported Media Type</h1>
<HR size="1" noshade="noshade"><p><b>type</b>
Status report</p><p><b>message</b>
<u>Unsupported Media Type</u></p>
<p><b>description</b> <u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (Unsupported Media Type).</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.23</h3>
</body>
我可以做什么错?谁能引导我走向正确的道路?感谢。
答案 0 :(得分:0)
最后我解决了自己。我的错误是我试图在URL中发布json(编码或什么)请求,而服务器可能没有任何方法来支持这样的请求。我还尝试了 ASIHTTPRequest ,不知道为什么ASIFormRequest无法正常工作。现在我得到了回应。
所以我将上面的代码更改为:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://api.esha.com/analysis?apikey=%@",ApiKey]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request addRequestHeader:@"Content-Type" value:@"application/json"];
[request setPostBody:(NSMutableData *)[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setDelegate:self];
[request startSynchronous];