2013-03-01 1 views
0

응용 프로그램에서 서버로 정보를 전달해야합니다. 특히 a와 b는 텍스트 형식으로 전달해야합니다. 다음은 WCF 서비스 코드입니다.iOS에서 WCF 서비스로의 인수 전달

public class iOSService 
{ 
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json) 
// To create an operation that returns XML, 
// add [WebGet(ResponseFormat=WebMessageFo rmat.Xml)], 
// and include the following line in the operation body: 
// WebOperationContext.Current.Outgoin gResponse.ContentType = "text/xml"; 
[OperationContract] 
public void DoWork() 
{ 
// Add your operation implementation here 
return; 
} 

// Add more operations here and mark them with [OperationContract] 


[OperationContract] 
public string iOSTest2(string a, string b) 
{ 
string res = ""; 
try 
{ 
res=(int.Parse(a) + int.Parse(b)).ToString(); 
} 
catch (Exception exp) 
{ 
res = "Not a number"; 
} 
return res; 
} 


} 

a 및 b를받은 후 서버는이를 더하고 합계를 다시 보냅니다.

그리고 여기가 아이폰 OS 응용 프로그램의 매개 변수를 서버에 전송하는 내 코드입니다 :

- (IBAction)test:(id)sender { 

    NSArray *propertyNames = [NSArray arrayWithObjects:@"23", @"342", nil]; 
    NSArray *propertyValues = [NSArray arrayWithObjects:@"a", @"b", nil]; 

    NSDictionary *properties = [NSDictionary dictionaryWithObjects:propertyNames forKeys:propertyValues]; 

    NSMutableArray * arr; 

    arr=[[NSMutableArray alloc]initWithObjects:properties, nil]; 
    NSLog(@"%@",arr); 

    NSError * error; 
    NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mathforyou.net/iOSservice.svc/iOSTest2"]]; 
    NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding]; 

    [request setValue:@"appliction/json" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPMethod:@"POST"]; 
    [request setHTTPBody:jsonData2]; 
    NSLog(@"JSON String: %@",jsonString); 
    NSError *errorReturned = nil; 
    NSURLResponse *theResponse =[[NSURLResponse alloc]init]; 
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned]; 
    if (errorReturned) { 
     //...handle the error 
     NSLog(@"error"); 
    } 
    else { 
     NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

     NSLog(@"%@",retVal); 
    } 
} 

그러나 서버는 나에게 다음과 같은 메시지에 응답 :

"ExceptionDetail":null,"ExceptionType":null,"Message":"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.","StackTrace":null 

을 그리고 여기에 엑스 코드의 로그입니다 :

2013-03-01 17:38:28.657 2231233122[3442:c07] (
     { 
     a = 23; 
     b = 342; 
    } 
) 
2013-03-01 17:38:28.659 2231233122[3442:c07] JSON String: [ 
    { 
    "a" : "23", 
    "b" : "342" 
    } 
] 
2013-03-01 17:38:29.054 2231233122[3442:c07] {"ExceptionDetail":null,"ExceptionType":null,"Message":"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.","StackTrace":null} 

PS 나는 친구를 도와달라고 부탁했다. 그러나 그는 객관적인 것을 모르기 때문에 C++만을위한 프로그램을 작성했고 코드는 작동하기 때문에 문제는 서버에 없다. 다음은 코드입니다.

string data = "{\"a\":\"560\",\"b\":\"90\"}"; 

byte[] bd = Encoding.UTF8.GetBytes(data); 

HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("http://www.mathforyou.net/IOSService.svc/iOSTest2"); 
wr.ContentType = "application/json"; 
wr.Method = "POST"; 
wr.ContentLength = bd.Length; 
Stream sw = wr.GetRequestStream(); 
sw.Write(bd, 0, bd.Length); 
sw.Close(); 
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse(); 
Stream s = resp.GetResponseStream(); 
byte[] bres = new byte[resp.ContentLength]; 
s.Read(bres, 0, bres.Length); 
string ans = Encoding.UTF8.GetString(bres); 
Console.WriteLine(ans); 

도와주세요, 나는 지치고 있습니다.

+0

을, 나는 IncludeExceptionDetailInFaults''를 켜기 시작하는 것 발생합니다. – Joshua

+0

서버 코드에 문제가 없다는 것을 알고 있다면 왜 포함 시켰습니까? –

+0

@ JoshCaswell 그냥 어떤 형식으로 인수를 전달해야하는지 알 수 있습니다. –

답변

2

코드를 복사하여 붙여 넣으면 Content-Type 값의 맞춤법이 잘못되어있는 것처럼 보입니다. application/json이어야하며, appliction/json으로 지정해야합니다.

또한 중요한지 확실하지 않지만 콘텐츠 길이를 명시 적으로 설정하지 않았습니다. 나는 setHTTPBody:가 당신을 위해 그것을하는 경우에 확실하지 않다.

+0

길이를 어떻게 얻고 쿼리에 추가합니까? –

+0

NSString * postLength = [NSString stringWithFormat : @ "% d", [jsonData2 length]]를 추가했습니다. [addValue 요청 : postLength forHTTPHeaderField : @ "Content-Length"]; 하지만 성공적으로 –

+0

'Content-Type'에 대한 오타를 수정 했습니까? 또한 오류가 무엇인지 알 수 있도록 추가 예외 세부 정보를 사용하도록 설정해야합니다. – Joshua

0

나는 여전히이 필요하면 모르겠지만, 다음 시도 : 그것은 그래서 당신은 실제 오류를 볼 수 있습니다 것이 좋습니다처럼 잘

[request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:jsonString forHTTPHeaderField:@"json"]; //<-- I added this line 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:jsonData2];