【发布时间】:2013-02-13 15:34:30
【问题描述】:
我有一个简单的 asp.net Web 服务,它返回 json 格式的数据。我想发送带有参数的http post请求以获取json数据。 如何发送请求和获取数据?
发帖请求:
POST /JsonWS.asmx/FirmaGetir HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length
firID=string
回答:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
我正在尝试一些代码,但它们不起作用。
NSString *firmadi =@"";
NSMutableData *response;
-(IBAction)buttonClick:(id)sender
{
NSString *firid = [NSString stringWithFormat:@"800"];
response = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]];
NSString *params = [[NSString alloc] initWithFormat:@"firID=%@",firid];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
response = [[NSMutableData data] retain];
}
else
{
NSLog(@"theConnection is null");
}
}
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)responsed
{
[response setLength:0];
NSURLResponse * httpResponse;
httpResponse = (NSURLResponse *) responsed;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[response appendData:data];
//NSLog(@"webdata: %@", data);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
NSLog(@"error with the connection");
[connection release];
[response release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
response = [[NSMutableData data] retain];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(@"%@",responseString);
}
【问题讨论】:
-
您是否尝试将请求中的 MIME 类型设置为“application/json”而不是“application/x-www-form-urlencoded”?
-
它来自我的网络服务,为什么我要更改这个设置?
-
您发布的代码有什么问题?
-
屏幕上只有一个按钮。当我按下按钮时,我想查看我的服务结果。但不会发生。
-
In didFinishLoading response = [[NSMutableData data] retain] 正在丢失您在使用之前下载的所有数据,请将其放在 NSString *responseString...
标签: iphone ios json http-post httprequest