2012-11-21 125 views
1

當試圖連接到下面的Web方法,「請求格式是無效的」返回:「請求格式無效」

public string myWebMethod(string test) 
{ 
    return "connected"; 
} 

這是客觀的C代碼:

NSString *seshID = @"test-session";  
NSString *post = [NSString stringWithFormat:@"test=%@", seshID]; 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 

NSString *comparisonURLString = SERVER_COMPARE_URL_STRING; 
NSURL *comparisonURL = [NSURL URLWithString: comparisonURLString]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:comparisonURL]; 

[request setHTTPMethod:@"POST"]; 
[request addValue:postLength forHTTPHeaderField:@"Content-Length"]; 

NSHTTPURLResponse *urlResponse = nil; 
NSError *error = nil; 
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; 

NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];  
NSLog(response); 

然而,如果我改變網絡方法,以便它不需要參數:

public string myWebMethod() 

並改變我obj-c cod中的相應行E要:

NSString *post = [NSString stringWithFormat:@""]; 

它的工作原理,與響應:

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">connected</string> 

任何人都可以解釋爲什麼後者似乎工作,但前者沒有?謝謝。

+1

您是否嘗試過提琴手來解決任何Web服務問題? – Jon

+0

@all: 原來我錯過了一行:'[request setHTTPBody:postData];' Mea culpa並感謝大家的建議。 – Robert

+0

@Jon:我對Fiddler不是很熟悉,但現在看看Fiddler2。歡呼的建議。 – Robert

回答

1

我在JAVA WebMethod和C#之間有類似的問題。該問題已通過創建一個不包含SoapHeader幷包含字符串[]的類string1來解決。

那麼對於你的榜樣,你可以試試這個

public string myWebMethod(string[] test) 
{ 
    return "connected"; 
} 

public string myWebMethod(char[] test) 
{ 
    return "connected"; 
} 

您可以檢查過與小提琴手什麼樣的數據是真的過去了。

+0

謝謝。原來我錯過了一行代碼,但我會接受這個答案,因爲它可以幫助別人.. – Robert